兼容性要求不高的情況下可以用a標(biāo)簽的download屬性,HTML5新增的
export function open (url, name) {
let a = document.createElement('a')
a.target = '_blank'
a.setAttribute('href', url)
if (name) {
a.setAttribute('download', name)
}
a.style.display = 'none'
document.body.appendChild(a)
let e = document.createEvent('MouseEvents')
e.initEvent('click', true, true)
a.dispatchEvent(e)
setTimeout(() => {
document.body.removeChild(a)
}, 1000)
}
以下情況可以支持

download屬性支持情況
可以看到,萬惡的IE不支持,所以下載下來就是后端指定的名稱或者默認(rèn)名稱
前端重命名文件名還有另一種方法:Blob
async download (url, name) {
if (window.navigator.msSaveBlob) { // msSaveBlob僅支持IE10+
const res = await api().get(url) // 獲取到文件的二進(jìn)制流
const blob = new Blob([res], { type: 'application/json;charset=utf-8' }) // application/vnd.openxmlformats-officedocument.wordprocessingml.document這里表示doc類型
const href = window.URL.createObjectURL(blob) // 創(chuàng)建下載的鏈接
try {
window.navigator.msSaveBlob(blob, name)
} catch (e) {
console.log(e)
}
window.URL.revokeObjectURL(href)
} else {
open(url, name) // 上面那個open函數(shù)
}
}
但是這種方法有一些弊端:
- 消耗內(nèi)存,下載大文件可能會崩
- 點擊下載之后,IE瀏覽器會先把文件下載到電腦(此時瀏覽器看起來沒有任何反應(yīng)),等下載完成再提示:是否保存文件;所以需要你手動在點擊下載的時候加個toast提示之類的
所以我覺得最好的辦法就是在后端返回文件名,既保證兼容性,又不占內(nèi)存