第1步:调用接口
var _this=this
this.axios({
url:this.HOST + api,
method:'post',
params:{
fileId:fileId //后端所需参数
},
responseType:'arraybuffer' //此处注意请求头,json,buffer,blob
}).then(res=>{
_this.transformBlobToUrl(res.data) // 将后端返回的blob转化成URL下载文件
})
第2步:处理返回值,并下载
function transformBlobToUrl(res, filename) {
let blob = new Blob([res.data])
if (res.data.type == "application/json") {
// 说明是普通对象数据,后台转换失败
const fileReader = new FileReader();
fileReader.readAsText(blob, "utf-8");
fileReader.onloadend = function () {
let dataJson = JSON.parse(fileReader.result);
// elementUI 消息提示
Message({
type: "warning",
message: dataJson.msg // 后端返回错误信息
});
};
} else {
let downloadElement = document.createElement('a')
let href = window.URL.createObjectURL(blob) //创建下载的链接
let fileName = filename ? filename : res.headers['content-disposition'] ? res.headers['content-disposition'].split(';')[1].split('=')[1] : new Date().getTime() + '.xlsx'
downloadElement.href = href
downloadElement.download = decodeURIComponent(fileName)//解码
document.body.appendChild(downloadElement)
downloadElement.click()
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(href)
}
}