我有一个生成PDF的动作类.该contentType
适当地设定.
public class MyAction extends ActionSupport { public String execute() { ... ... File report = signedPdfExporter.generateReport(xyzData, props); inputStream = new FileInputStream(report); contentDisposition = "attachment=\"" + report.getName() + "\""; contentType = "application/pdf"; return SUCCESS; } }
我action
通过Ajax调用来调用它.我不知道将此流传递给浏览器的方法.我尝试过一些东西,但没有任何效果.
$.ajax({ type: "POST", url: url, data: wireIdList, cache: false, success: function(response) { alert('got response'); window.open(response); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert('Error occurred while opening fax template' + getAjaxErrorString(textStatus, errorThrown)); } });
以上给出了错误:
您的浏览器发送了此服务器无法理解的请求.
小智.. 114
这是我如何工作的方式
$.ajax({
url: '',
success: function(data) {
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="";
link.click();
}
});
$.ajax({
url: '',
success: download.bind(true, "", "")
});
这是我如何工作的方式
$.ajax({
url: '',
success: function(data) {
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="";
link.click();
}
});
你不一定需要Ajax.只是一个环节是不够的,如果你设置
content-disposition
到attachment
服务器端代码.这样父页面就会保持打开状态,如果这是你的主要关注点(为什么你会不必要地选择Ajax呢?).此外,没有办法很好地同步处理这个问题.PDF不是字符数据.这是二进制数据.你不能做的事情$(element).load()
.您想对此使用全新的请求.因为那pdf
是非常合适的.
为了更多地帮助您使用服务器端代码,您需要详细了解所使用的语言并发布代码尝试的摘录.
与我提到的jQuery插件相比,更新 Mayur的答案看起来非常有前途且非常简单.
这就是我如何解决这个问题.
乔纳森·阿门德在这篇文章中的答案对我帮助很大.
以下示例已简化.
有关更多详细信息,上面的源代码能够使用JQuery Ajax请求(GET,POST,PUT等)下载文件.它还有助于将参数上传为JSON并将内容类型更改为application/json(我的默认值).
在HTML源:
一个带有两个输入文本,一个选择和一个按钮元素的简单表单.
在JavaScript的网页来源:
点击按钮时的简单事件.它创建了一个AjaxDownloadFile对象.AjaxDownloadFile类源代码如下.
该AjaxDownloadFile类来源:
var AjaxDownloadFile = function (configurationSettings) { // Standard settings. this.settings = { // JQuery AJAX default attributes. url: "", type: "POST", headers: { "Content-Type": "application/json; charset=UTF-8" }, data: {}, // Custom events. onSuccessStart: function (response, status, xhr, self) { }, onSuccessFinish: function (response, status, xhr, self, filename) { }, onErrorOccured: function (response, status, xhr, self) { } }; this.download = function () { var self = this; $.ajax({ type: this.settings.type, url: this.settings.url, headers: this.settings.headers, data: this.settings.data, success: function (response, status, xhr) { // Start custom event. self.settings.onSuccessStart(response, status, xhr, self); // Check if a filename is existing on the response headers. var filename = ""; var disposition = xhr.getResponseHeader("Content-Disposition"); if (disposition && disposition.indexOf("attachment") !== -1) { var filenameRegex = /filename[^;=\n]*=(([""]).*?\2|[^;\n]*)/; var matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) filename = matches[1].replace(/[""]/g, ""); } var type = xhr.getResponseHeader("Content-Type"); var blob = new Blob([response], {type: type}); if (typeof window.navigator.msSaveBlob !== "undefined") { // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed. window.navigator.msSaveBlob(blob, filename); } else { var URL = window.URL || window.webkitURL; var downloadUrl = URL.createObjectURL(blob); if (filename) { // Use HTML5 a[download] attribute to specify filename. var a = document.createElement("a"); // Safari doesn"t support this yet. if (typeof a.download === "undefined") { window.location = downloadUrl; } else { a.href = downloadUrl; a.download = filename; document.body.appendChild(a); a.click(); } } else { window.location = downloadUrl; } setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // Cleanup } // Final custom event. self.settings.onSuccessFinish(response, status, xhr, self, filename); }, error: function (response, status, xhr) { // Custom event to handle the error. self.settings.onErrorOccured(response, status, xhr, self); } }); }; // Constructor. { // Merge settings. $.extend(this.settings, configurationSettings); // Make the request. this.download(); } };
我创建了这个类来添加到我的JS库中.它是可重复使用的.希望有所帮助.
您可以使用此插件创建表单,然后提交表单,然后将其从页面中删除.
jQuery.download = function(url, data, method) { //url and data options required if (url && data) { //data can be string of parameters or array/object data = typeof data == 'string' ? data : jQuery.param(data); //split params into form inputs var inputs = ''; jQuery.each(data.split('&'), function() { var pair = this.split('='); inputs += ''; }); //send request jQuery('') .appendTo('body').submit().remove(); }; }; $.download( '/export.php', 'filename=mySpreadsheet&format=xls&content=' + spreadsheetData );
这对我有用.在这里找到这个插件
对我来说有用的是以下代码,因为服务器功能正在检索 File(memoryStream.GetBuffer(), "application/pdf", "fileName.pdf");:
$http.get( fullUrl, { responseType: 'arraybuffer' }) .success(function (response) { var blob = new Blob([response], { type: 'application/pdf' }); if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob); // for IE } else { var fileURL = URL.createObjectURL(blob); var newWin = window.open(fileURL); newWin.focus(); newWin.reload(); } });