如何在IE 9中使用XMLHTTPRequest响应下载XSLX或DOCX文件?我只需要IE 9解决方案。
此代码适用于纯文本和csv文件但是当我尝试下载XSLX或DOCX文件时没有任何反应。
响应来自一个响应内容类型设置为
的java servletapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
下载文件所需的javascript函数。
function submitForm(command, event) {
disableButtons();
var form = $('form[name=myForm]');
var dataString = form.serialize();
var xhr = new XMLHttpRequest();
xhr.open('POST', myURL, true);
//tested => xhr.responseType = 'arraybuffer';
//tested => try { xhr.responseType = "arraybuffer"; } catch (e) { }; application/zip
//tested => try { xhr.responseType = "msxml-document"; } catch (e) { };
xhr.onreadystatechange = function() {
if(xhr.readyState == 4){
// xhr is complete (200 for web servers, 0 for local files in IE)
if ((xhr.status == 200)||(xhr.status == 0)){
// good
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 URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
var frame = document.createElement('iframe');
document.body.appendChild(frame);
frame.contentWindow.document.open(type, "replace");
frame.contentWindow.document.write(xhr.responseText); //tried also responseXML
frame.contentWindow.document.close();
frame.contentWindow.focus();
frame.contentWindow.document.execCommand('SaveAs', true, filename);
document.body.removeChild(frame);
setTimeout(function () {
URL.revokeObjectURL(downloadUrl);
}, 100); // cleanup
} else{
// error
}
}
}
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(dataString);
}
答案 0 :(得分:0)
你不能,不能使用XMLHTTPRequest和IE9 您可以使用表单提交请求并将其目标设置为iframe,响应内容处置标头设置为附件,这将导致保存对话框打开。
<form name="myForm" target="somehiddeniframe>
..
</form>