[js]前端下载后端返回的blob文件流,并保留原有名称

需求

后台需要根据选定的 厂商和设备型号,生成对应的excel表格模版
通过接口返回文件流,采用blob接收


image.png

问题

直接将blob文件流存储为指定文件名,前端还要自己起个名字
后在接口response的header中发现了如下参数content-disposition,那么优雅的保存blob的文件就有了方法


image.png

代码

//axios的请求方式
axios({
        url: url+"?a=1&b=2",
        method: "get",
        responseType:'blob'
      })
        .then( res => {
          let fileName = (res.headers['content-disposition'].split("="))[1]
          let blob = res.data
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                /*
                  * For IE
                  * >=IE10
                  */
                window.navigator.msSaveBlob(blob, fileName);
            } else {
                /*
                  * For Non-IE (chrome, firefox)
                  */
                var URL = window.URL || window.webkitURL;
                var objectUrl = URL.createObjectURL(blob);
                if (fileName) {
                    var a = document.createElement('a');
                    if (typeof a.download === 'undefined') {
                        window.location = objectUrl;
                    } else {
                        a.href = objectUrl;
                        a.download = fileName;
                        document.body.appendChild(a);
                        a.click();
                        a.remove();
                    }
                } else {
                    window.location = objectUrl;
                }
            }
        })
        .finally(r => {
        });

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容