downloadjs浏览器下载文件
原创
©著作权归作者所有:来自51CTO博客作者明知山的原创作品,请联系作者获取转载授权,否则将追究法律责任
npm install downloadjs
import download from "downloadjs"
download(fileUrl, fileName);
自己实现了类似的效果
function download(fileUrl,) {
const request = new XMLHttpRequest()
request.open('get', fileUrl)
request.responseType = 'blob'
request.onreadystatechange = (res) => {
if (res.currentTarget.readyState == 4 && res.currentTarget.status == 200) {
const url = window.URL.createObjectURL(res.currentTarget.response)
const link = document.createElement('a')
link.href = url
link.setAttribute('download', fileName ? fileName : new Date().getTime())
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
request.send()
}
如果下载的文件报跨域,就用a标签
下载
function downloadFile(fileUrl,) {
let a = document.createElement('a');
a.href = fileUrl;
a.download = fileName ? fileName : new Date().getTime();
a.click();
}