调用接口
axios({
url:url,
method:'post',
data:params, //参数
responseType:'arraybuffer' //此处注意请求头,json,buffer,blob
}).then(res=>{
this.download(res) // 将后端返回的blob转化成URL下载文件
})
处理返回值,下载
function download (response) {
if (response.status !== 200) return
let blob = new Blob([response.data]);
if (response.headers['content-type'] === "text/html;charset=UTF-8") { //如果返回的是json,则代表有错误,下面将文件流重新转为json,抛出错误
let reader = new FileReader()
reader.readAsText(blob)
reader.onloadend = (event) => {
let content = JSON.parse(reader.result)
Message({
message: content.msg || '程序发生异常,请联系管理员!',
type: 'error',
duration: 3 * 1000
});
}
} else { //下载文件
let disposition = response.headers['content-disposition']
let [, filename, excelBoolean] = disposition.split(';')
// let [,flag] = excelBoolean.split('=')
// 转译以URL形式编码的文件名
filename = decodeURI(filename.split('=')[1])
let a = document.createElement("A")
a.href = window.URL.createObjectURL(blob)
a.download = filename
a.click()
}
}