js 返回的数据流 进行文件下载

发起请求,后台返回二进制数据流,进行下载

 1 import request from "@/router/axios";     //引入封好的请求
 2 
 3 // 请求方法
 4 export function getDown(obj) {
 5   return request({
 6     url: "接口",
 7     method: "get",
 8     params: obj,
 9     responseType: "arraybuffer",          //设置请求的方式,后台返回数据流,就要设置 arraybuffer 。
10   }).then(({ data }) => {
11     // 处理返回的文件流(data  是后台返回的数据流) new Blob  里面,type 是要下载的各类文件类型
12     let blob = new Blob([data], { type: "application/vnd.ms-excel" });
13     let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob);
14     let downFile = document.createElement("a");
15     let fileName = "设置下载出来的文件名.xls";       
16     downFile.style.display = "none";
17     downFile.href = objectUrl;
18     downFile.download = fileName;          // 下载后文件名
19     document.body.appendChild(downFile);
20     downFile.click();
21     document.body.removeChild(downFile);   // 下载完成移除元素
22     // window.location.href = objectUrl
23     window.URL.revokeObjectURL(objectUrl); // 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。
24   });
25 }                

 

 

根据文件地址下载:

 1 blodDownloadFn(data,fildName){
 2             let url = window.URL.createObjectURL(new Blob([data]))
 3                 let link = document.createElement('a')
 4                 link.style.display = 'none'
 5                 link.href = url
 6                 link.setAttribute('download', fildName)
 7                 document.body.appendChild(link)
 8                 link.click()
 9                 document.body.removeChild(link) //下载完成移除元素
10                 window.URL.revokeObjectURL(url) //释放掉blob对象
11         },
12 
13     // 下载文件事件
14     downLoadFile(info=‘文件信息,无用,只需找到http地址放入下面URL即可’,source=‘来源,无用’){
15         console.log(source,"下载文件",info);
16         let fileName = info.response.filename.split('.')[1] 
17         let url = info.origin_url || info.url || info.thumbUrl
18         const xhr = new XMLHttpRequest();
19         xhr.open('get', url, true);
20         xhr.responseType = 'blob';
21         xhr.onload = ()=> {
22             // 返回文件流,进行下载处理
23             this.blodDownloadFn(xhr.response,info.name +'.'+ fileName);
24         };
25         xhr.send(); // 不要忘记发送
26     },

 

posted @ 2022-05-17 12:01  伊人兮明眸秋水  阅读(1564)  评论(0编辑  收藏  举报