axios下载流文件

  • 1.接口返回的流和头部:

img

img

  • 2.下载流文件的代码

img

方法一:是用了插件 https://github.com/kennethjiang/js-file-download

方法二:是用了 blob

不管哪种方法,记得设置 responseType !!!!!

附上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 导出
exportBill:function () {

let url_post = Vue.prototype.api.apiList.EXPORT_BILL;

let params_post = {
orderStartDate: this.timepickerDateFormat(this.rangeTime[0]) || this.rangeTime[0] || '',
orderEndDate: this.timepickerDateFormat(this.rangeTime[1]) || this.rangeTime[1] || '',
prodCode: this.prodId,
promoteFlag: this.promotionSiteId,
policyStatusList: this.tableBillStateCheckedData,
};

Vue.axios.post(url_post,params_post,{responseType: 'arraybuffer'}).then((res) => {

let fileName = res.headers['content-disposition'].match(/fushun(\S*)xls/)[0];

fileDownload(res.data,fileName); //如果用方法一 ,这里需要安装 npm install js-file-download --save ,然后引用 var fileDownload = require('js-file-download'),使用详情见github;
      // let blob = new Blob([res.data], {type: "application/vnd.ms-excel"});

      // let objectUrl = URL.createObjectURL(blob);

      // window.location.href = objectUrl;

    }).catch(function (res) {}); },
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
axios.post(url, param, {
responseType: 'blob'
}).then((res) => {
console.log('res', res);
const blob = res.data;
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = (e) => {
const a = document.createElement('a');
a.download = `文件名称.zip`;
// 后端设置的文件名称在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"20181211191944.zip\"",
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
}).catch((err) => {
console.log(err.message);
});



this.$axios.post('URL', postData {responseType: 'blob'}).then((res) => {
console.log(res);
let blob = new Blob([res.data], {type: "audio/x-wav"});
// let objectUrl = URL.createObjectURL(blob);
// window.location.href = objectUrl;

let url = window.URL.createObjectURL(blob)
this.audioList.url = url
this.audioList.totalTime = this.interactiveRecordData.dialogueDuration
})