工作中经常会有下载文件的功能,一般后台会以返回url或者流文件的形式,url直接打开就好,不多说,下面是流文件的下载方式。
直接上代码
this.$http({
url: 'xx/xx',
method: 'get',
responseType: 'blob',
params: {}
}).then(({data}) =>{
const content = data
const blob = new Blob([content], {type: 'application/pdf'})
var name = 'pdf.pdf'
const elink = document.createElement('a')
elink.download = name
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
this.loadpdf=false
})
本段代码最最最重要的是不使用封装好的接口访问方式,改为上述代码形式,刚开始找到的时候我也是直接复制接口返回成功里面的代码,结果各种不对,后来发现 responseType: ‘blob’ 这段是最致命的。