vue项目中,后端返回文件流,axios发送post请求下载文件
axios拦截处理
复制代码
service.interceptors.response.use(
response => {
// 导出
const headers = response.headers
if (headers[‘content-type’] === ‘application/octet-stream;charset=utf-8’) {
return response.data
}
…
},
error => {
return Promise.reject(error)
}
)
复制代码
接口设置
复制代码
export function export(params = {}) {
return request({
url: ‘/export’,
method: ‘post’,
data: params,
responseType: ‘blob’
})
}
复制代码
请求处理
复制代码
exportClick () {
export().then(res => {
const content = res
const blob = new Blob([content])
const fileName = ‘导出信息.xlsx’
if (‘download’ in document.createElement(‘a’)) { // 非IE下载
const elink = document.createElement(‘a’)
elink.download = fileName
elink.style.display = ‘none’
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else { // IE10+下载
navigator.msSaveBlob(blob, fileName)
}
})
}
复制代码
这里用到了Blob对象,这里是从服务器接收到的文件流(content-type:application/octet-stream)创建blob对象并使用该blob 创建一个指向类型数组的URL,将该url作为a标签的链接目标,然后去触发a标签的点击事件从而文件下载
转自:https://www.cnblogs.com/rongjuan/p/9644676.html