说明:
- 使用
a
链接的download
方法 - 调用:
this.downloadFile_1('文件名','url链接')
- 本地无法下载的话,可以试试放到线上
- 文件名要加
.pdf
后缀
方法一:
downloadFile_1(fileName, filePath) {
if (!filePath) {
return
}
// let url = window.URL.createObjectURL(new Blob([filePath]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = filePath
link.setAttribute('download', `${fileName}.pdf`)
document.body.appendChild(link)
link.click()
},
方法二:
downloadFile_2(fileName, filePath) {
var ajax = new XMLHttpRequest()
ajax.open('GET', filePath, true)
ajax.setRequestHeader('Cache-Control', 'no-cache')
ajax.setRequestHeader('Access-Control-Allow-Origin', '*')
ajax.responseType = 'blob'
ajax.onload = (e) => {
console.log(e)
let res = e.target.response
// let blob = new Blob([res],{type: "application/pdf;charset=UTF-8"}) // 这里的res为后端返回的流数据
let blob = new Blob([res])
let aLink = document.createElement('a')
aLink.download = `${fileName}.pdf` // 下载文件的名字
aLink.href = URL.createObjectURL(blob)
aLink.click()
}
ajax.send()
},