1.写axios接口 responseType: 'blob' 这个是设置请求返回类型的
import axios from 'axios'
`export const uploadFileRequest = (url, body, params) => {
let token = getTokens()
let queryParams = { 'access_token': token.access_token }
Object.assign(queryParams, params)
return axios({
method: 'post',
url: `${base}${url}`,
data: body,
params: queryParams,
responseType: 'blob'
})
}`
2.调用接口,拿到返回值,模拟超链接点击下载文件
exportLogZIP('/download', '',{ id: 1 }).then(res => {
const content = res
const blob = new Blob([content])
const fileName = 'LOG.zip'
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)
}
})
例子 fetch 导出表格
`let params = {
batchNum: val,
id: id,
};
fetch("/api/billBatch/export", {
method: "post",
headers:{
'Content-Type' : 'application/json',
'admin_token': cookies.get('admin_token'),
},
body: JSON.stringify(params),
responseType: "blob",
}).then(res => {
return res.blob();
}).then(content => {
const blob = new Blob([content],{type: 'application/vnd.ms-excel'});
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)
}
}).catch(r=>{
})`
`