如何使用角度帖子从Internet Explorer中的webapi下载文件?

时间:2016-06-22 10:48:54

标签: javascript angularjs

我正在使用angularjs http post从按钮点击的Web Api下载文件。我的代码在谷歌浏览器和Firefox中正常工作,但它在Internet Explorer中不起作用。这是我的代码

$scope.CallApi = function () {
        $http({
            url: some url,
            dataType: 'json',
            method: 'POST',
            data: null,
            responseType: 'arraybuffer',    

        }).success(function (responsedata, status, xhr) {           
            var file = xhr('Content-Disposition');
            console.log(file); 
            var filename = file.substr(21, 7);
            $scope.value = responsedata;
            var fileName = filename;
            var blob = new Blob([responsedata], { type: "application/octet-stream" });
            var url = URL.createObjectURL(blob);
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.style = "display: none";
            a.href = url;
           a.download = fileName;        

        }).error(function (error) {
                alert("Error Found" + " : " + error);
            });
    };

以上代码在IE中不起作用,我不想使用FileSaver.js扩展是否还有其他方法可以从Internet Explorer中的api下载文件。下面我附上了我在Internet Explorer中收到的错误的屏幕截图.... enter image description here 提前谢谢.....

1 个答案:

答案 0 :(得分:1)

这是在IE中下载的一种方式

  if (window.navigator.msSaveOrOpenBlob){
      // base64 string
      var base64str = response;
      // decode base64 string, remove space for IE compatibility
      var newstr =base64str.replace(/\s/g, '');
      var binary = atob(newstr);
      // get binary length
      var len = binary.length;
      // create ArrayBuffer with binary length
      var buffer = new ArrayBuffer(len);
      // create 8-bit Array
      var view = new Uint8Array(buffer);

      // save unicode of binary data into 8-bit Array
      for (var i = 0; i < len; i++) {
        view[i] = binary.charCodeAt(i);
      }

      // create the blob object with content-type "application/csv"               
      var blob = new Blob( [view], { type: mimeType });
      window.navigator.msSaveOrOpenBlob(blob, "Name your file here");
}

这里mimeType将是application / octet-stream,响应是你的base64字符串。