[聚合文章] 文件下载的一些坑(IE 11,edge)angular2为例

Angular 2017-10-01 14 阅读

最近项目里关于文件下载的功能遇到了一些坑,项目是用angular2(其实是4不过为了和angularJS1.x区分)写的,所以以这个为例子,但是其实这个坑是所有的都有。
首先前端发送一个get请求,后端返回application/octet-stream类型
首先加一个responseType

this.http.get(url, {      withCredentials: true,      responseType : 3    })

responseType分别对应的类型

export declare enum ResponseContentType {Text = 0,Json = 1,ArrayBuffer = 2,Blob = 3,}

我这里是二进制流所以用3
返回之后处理下得到下载的链接

const blob1 = res.blob();const objectUrl = URL.createObjectURL(blob1);

或者

const blob = new Blob([res['_body']],{type: "application/x-download"});const objectUrl = URL.createObjectURL(blob);

一般情况下下载触发

const a = document.createElement('a');document.body.appendChild(a);a.setAttribute('style', 'display:none');a.setAttribute('href', url);a.setAttribute('download', name);a.click();URL.revokeObjectURL(url);

但是要触发下载后再释放链接,否则就会获取不到链接下载失败

 // 触发下载后再释放链接        a.addEventListener('click', function() {          URL.revokeObjectURL(url);          document.getElementById('download').remove();        });

但如果按这样会有兼容问题,IE无法触发下载。微软提供了一个解决方案。
navigator.msSaveBlob(res['blob'], name);

所以整体代码就是

 const uA = window.navigator.userAgent;    const isIE = /msie\s|trident\/|edge\//i.test(uA) && !!("uniqueID" in document || "documentMode" in document || ("ActiveXObject" in window) || "MSInputMethodContext" in window);const url = URL.createObjectURL(res['blob']);        const a = document.createElement('a');        document.body.appendChild(a);        a.setAttribute('style', 'display:none');        a.setAttribute('id', 'download');        a.setAttribute('href', url);        a.setAttribute('target', '_blank');        a.setAttribute('download', name); //这个name是下载名.后缀名        if (isIE) {          // 兼容IE11无法触发下载的问题          navigator.msSaveBlob(res['blob'], name);        } else {          a.click();        }        // 触发下载后再释放链接        a.addEventListener('click', function() {          URL.revokeObjectURL(url);          document.getElementById('download').remove();        });

以上就基本实现了兼容。不过在Safari的10以下版本还是无法触发下载,不知道还有没有其他的解决方案。

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。