PDF直接下载问题
浏览器中,pdf文件开发为预览而非直接下载
pdf文件与页面 不存在跨域问题,解决方案
handleDownload (record) {
var oReq = new XMLHttpRequest()
var URLToPDF = record.url
oReq.open('GET', URLToPDF, true)
oReq.responseType = 'blob'
oReq.onload = function () {
var file = new Blob([oReq.response], {
type: 'application/pdf'
})
const url = window.URL.createObjectURL(file)
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', `${record.name}_${moment().format('YYYYMMDD')}.pdf`)
document.body.appendChild(link)
link.click()
}
oReq.send()
}
pdf文件与页面 存在跨域问题,解决方案
egg.js 将文件地址转成文件流
async pdfToBlob() {
const { ctx } = this;
const params = ctx.request.body;
const result = await this.ctx.curl(params.url);
ctx.set('Content-Type', 'application/pdf')
ctx.body = result.data;
}
vue 下载文件
downloadPdf({ 'url': record.url }).then(res => {
const BLOB = new Blob([res])
const url = window.URL.createObjectURL(BLOB)
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', `***`)
document.body.appendChild(link)
link.click()
})
```javascript
// 下载pdf
export function downloadPdf (parameter) {
return axios({
url: '***',
method: 'post',
data: parameter,
responseType: 'blob'
})
}