可能一般通過(guò)后臺(tái)下載excel,會(huì)直接寫在a標(biāo)簽的href中用get請(qǐng)求,直接返回文件流,瀏覽器會(huì)自動(dòng)識(shí)別,
但是通過(guò)post下載可能有些問(wèn)題需要注意
在axios請(qǐng)求中設(shè)置responseType的類型為blob,不然會(huì)亂碼,這里可以打印出來(lái)看返回的類型,如果引入了mock.js,會(huì)改變后端傳入的文件流,變成string類型,所以
重點(diǎn)是看一下返回的類型,設(shè)置的blob是否有效,是否被改變
export function DownloadDb(data) {
return fetch({
url: '/downloadExcel',
method: 'post',
data,
responseType: 'blob'
})
}
DownloadDb({ title, values }).then(res => {
const blob = new Blob([res], {
type: 'application/vnd.ms-excel;charset=utf-8'
})
let fileName =
'渠道報(bào)表' + parseTime(new Date(), '{y}-{m}-u0z1t8os') + '.xls'
// fileDownload(res, fileName)
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 對(duì)象
document.body.removeChild(elink)
} else {
// IE10+下載
navigator.msSaveBlob(blob, fileName)
}
})
Object.keys() Object.values()無(wú)法保證對(duì)象的順序輸出