文件下载post请求,返回文件流转换zip,

 

 最近一个需求是批量下载文件,最后打包成zip包,post请求,

因为是文件流下载,所以在取后台数据的时候,要多传递一个【responseType: ‘blob’】这个参数

 1 download() {
 2       this.tableLoading = true;
 3       console.log(this.selectionLen);
 4       let docIds = [];
 5       this.selectionLen.forEach((item, index) => {
 6         docIds.push(item.id);
 7       });
 8       let params = {
 9         zipName: "downloadFile",
10         ids: docIds,
11         company: this.userinfo.account_name
12       };
13 
14       axios({
15         // 用axios发送post请求
16         method: "post",
17         url:
18           "http://xxx/pm/project/deliverable/download/zip", // 请求地址
19         data: params, // 参数
20         headers: {
21           "content-type": "application/json; charset=utf-8"
22         },
23         responseType: "blob" // 表明返回服务器返回的数据类型
24       }).then(res => {
25         this.tableLoading = false;
26         this.downloadFile(res.data);
27       });
28     },
 1 downloadFile(data) {
 2       let blob = new Blob([data], { type: "application/zip" });
 3       let url = window.URL.createObjectURL(blob);
 4       const link = document.createElement("a"); // 创建a标签
 5       link.href = url;
 6       let date = new Date();
 7       link.download = "fileDown" + FormatTime("YYYY-mm-dd HH:MM", date); // 重命名文件
 8       link.click();
 9       URL.revokeObjectURL(url); // 释放内存
10     }

最后成功下载文件

posted @ 2020-02-13 16:17  博仔show  阅读(5017)  评论(0编辑  收藏  举报