如何从IE上的GET XMLHttpRequest响应下载文件?

时间:2015-01-05 10:57:41

标签: ajax internet-explorer xmlhttprequest

我正在使用XMLHttpRequest GET请求进行文件下载:

var filename = 'data.zip';
var request = new XMLHttpRequest();
request.open('GET',  "/solfwk/srp/exportImportService/export", true);
request.responseType = 'blob';
request.setRequestHeader("ALFSSOAuthNToken", token);
request.setRequestHeader("Content-Type", "application/json");
request.setRequestHeader("Accept", "application/json");
request.onload = function() {
   var link = document.createElement('a');
   document.body.appendChild(link);
   link.href = window.URL.createObjectURL(request.response);
   link.download = filename;
   if(window.navigator.userAgent.indexOf("MSIE") > 0) {
      link.text = "Start...";                                        
      $('#messageExport').empty().append(link);
   } else {
      link.click();
   }
   $.unblockUI();
};
request.send();

对于非IE浏览器link.click()有效,但对于IE则不然。知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

我使用msSaveBlob或msSaveOrOpenBlob函数找到了这样的解决方案:http://msdn.microsoft.com/en-us/library/ie/hh779016(v=vs.85).aspx

答案 1 :(得分:-1)

用于IE:

 var request = new ActiveXObject("Microsoft.XMLHTTP");

要确定浏览器中是否有XmlHttpRequest,请使用以下代码:

 if (window.XMLHttpRequest) {
      request = new XMLHttpRequest();
 } else {
      request = new ActiveXObject("Microsoft.XMLHTTP");
 }