我正在通过 Ajax 和 VRaptor 直接下载 xls,VRaptor 使您的论文直截了当,并提供文件如下代码:
public Download geraExcel() {
File arquivo = //generate file
return new FileDownload(file, "MyFile.xls", "application/vnd.ms-excel", true);
}
问题是在 ajax 成功中接收这个文件,我有一个代码可以做到这一点,它非常适合 txt,问题是 xls 打开已损坏,我很长时间研究解决方案来解决问题,所有的都是不成功,继续文件损坏。如果有人知道另一种使它起作用的方法,我会感谢你。Ajax.success 以下代码:
success: function(response, status, xhr) {
// check for a filename
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();
//Here is the problem, the original is about 15k,
// but the download file is about 26K
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}