首先下载需要用到的插件 js-file-download
npm install js-file-download --save
在导出的组件引入fileDownload
import fileDownload from 'js-file-download'
使用
orderExport(){
var self = this;
/*responseType: 'arraybuffer' 设置该值能够改变响应类型 ArrayBuffer对象*/
this.$axios.post('/export',{id},{ responseType: 'arraybuffer'}).then(result => {
//实际调用
var head = result.headers['content-type'];
/*这里如果导出报错后台返回错误信息为json格式,判断headers为application/json时弹出错误信息*/
if(head && head.toLowerCase().indexOf('application/json') != -1){
/*ab2str() 该方法是ArrayBuffer转字符串,该方法文章下方有贴出。*/
/*由于我们responseType指定相应类型为ArrayBuffer对象,所以我们需要进行转换后再弹出提示*/
self.ab2str(result.data,function(str){
var json = JSON.parse(str)
self.$message.warning({
showClose: true,
message: result.msg
});
});
}else{
/*从后台响应headers中取出文件名fileName*/
let fileName = result.headers['content-disposition'].split('=')[1];
/*fileDownload方法第一个参数为后台响应Buffer流,第二个参数为下载文件名*/
fileDownload(result.data,decodeURI(fileName));
}
})
},
ArrayBuffer转字符串
ab2str(u,f) {
var b = new Blob([u]);
var r = new FileReader();
r.readAsText(b, 'utf-8');
r.onload = function (){if(f)f.call(null,r.result)}
},