request统一封装:
const contentDisposition = response.headers['content-disposition'] // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;有时候会报错原因是content-disposition在不同环境下有大小写的不同(可用toLowerCase方法取值);
const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
const result = patt.exec(contentDisposition)[1]
const returnData = {
data: res,
filename: result
}
console.log('下载', returnData)
return returnData;
接口设置:
export function downloadFile(data) {
return request({
responseType: 'blob', // 重点,必须设置
url: url,
method: 'post',
params: data
})
}
方法:
fileDownloadBlob(data, filename) {
if (window.navigator.msSaveBlob) {
const blobObject = new Blob([data], { type: 'text/plain;charset=UTF-8' })
window.navigator.msSaveBlob(blobObject, filename)
} else {
const url = window.URL.createObjectURL(new Blob([data]))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
}
},
使用:
this.fileDownloadBlob(res.data, res.filename) // res.data是后台返回得文档流