最近在项目中遇到一个需求,用户可以点击按钮下载文件,后端返回给前端的是文件的绝对地址。
最开始我是用的windown.open()
实现,但是使用这个方法下载的文件名是乱码,测试要求将文件名固定。通过查阅资料,我了解到可以将url地址转为blob文件对象从而实现对文件的重命名,代码如下:
// 将文件路径转为blob
function getBlob (url) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest()
// 避免 200 from disk cache
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response)
}
}
xhr.send()
})
}
function saveAs (blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename)
} else {
const anchor = document.createElement('a')
const body = document.querySelector('body')
anchor.href = window.URL.createObjectURL(blob)
anchor.download = filename
anchor.style.display = 'none'
body.appendChild(anchor)
anchor.click()
body.removeChild(anchor)
window.URL.revokeObjectURL(anchor.href)
}
}
export async function download (url, newFileName) {
const blob = await getBlob(url)
saveAs(blob, newFileName)
//newFileName是文件的名字,要加上文件的拓展名
}