【问题标题】:How to download the file from webapi in Internet Explorer using angular post?如何使用 Angular Post 从 Internet Explorer 中的 webapi 下载文件?
【发布时间】:2016-06-22 20:52:54
【问题描述】:

我正在使用 angularjs http post 在单击按钮时从 Web Api 下载文件。我的代码在 Google Chrome 和 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 中遇到的错误的屏幕截图...... 提前谢谢你.....

【问题讨论】:

  • 对不起,我在中间插入了图片....

标签: javascript angularjs


【解决方案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,response 是你的 base64 字符串。

【讨论】:

  • 感谢 Rakeschand 提供宝贵的 cmets,但它使用第三方工具下载是任何其他不使用第三方工具的方式,就像我以前使用 filesaver.js 所做的那样,但 filesaver.js 是我不需要这样的第三方工具
  • window.navigator.msSaveOrOpenBlob 未定义
  • 不,它不是 FileSaver.js,您是否在 IE 中尝试过,因为在 IE 中它不会未定义。
  • 但其他浏览器不支持'msSaveOrOpenBlob'
  • 您说您的代码可以在其他浏览器中运行。您可以将该代码放在其他部分。
猜你喜欢
  • 2016-12-23
  • 2022-01-10
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
相关资源
最近更新 更多