我在处理Ajax的excel文件下载时遇到了一些问题。我在另一个网页上找到了这个源代码,我在我的网络项目中复制了它:
$.ajax({
type: "POST",
url: "myStrutsAction.action",
data: {p1:p1, p2:p2},
success: function(response, status, xhr){
disableMyLoadingUserPopupScreen();
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, '');
disposition);
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
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);
}
}
});
这种代码显示用于保存或打开特定 excel 文件的用户对话框。但是如果我尝试打开Excelfile,则文件已损坏并且无法打开(我在Notepad ++编辑器中查看过,但在这里我看到一些神秘的字符):
这是我在服务器上的 Struts2 执行方法:
public String execute(){
// Create Excel File
returnFileAsStream("myExcelfile");
return null;
}
在此方法中,我编写了 HTTP 响应标头:
private void returnFileAsStream(final String filename) throws IOException {
final InputStream is = new FileInputStream(filename);
OutputStream os = null;
try {
response.setContentType("application/octet-stream");
response.setHeader("Cache-Control", "maxage=3600");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "attachment; filename="" + filename + """);
os = response.getOutputStream();
int length;
byte buf[] = new byte[1024];
while ((length = is.read(buf)) > 0) {
os.write(buf, 0, length);
}
is.close();
os.close();
} finally {
// other code, not important
}
}
没错,不可能用Ajax处理文件下载?我认为,这是问题所在,我想用二进制数据而不是文本数据处理一些步骤,而 Ajax 不能用二进制代码处理一些步骤?
将内容类型设置为 :
对于 BIFF .xls文件
application/vnd.ms-excel
对于 Excel2007 及以上.xlsx文件
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet