需求:后台返回PDF文件流,前端实现下载到本地
1.封装请求
1.引入axios
2.getToken字段
import axios from 'axios'
export function getFilePDF(url, params) {
console.log('params==', params)
return new Promise((resolve, reject) => {
axios({
method: "GET",
url: process.env.VUE_APP_API_BASE_URL + url,
headers: {
'token': getToken()
},
responseType: 'arraybuffer',//必填项!!!
params: {
...params
}
}).then((res) => {
resolve(res)
})
.catch((err) => {
reject(err)
});
})
}
responseType: 'arraybuffer'//必填!!!
2.调用
页面内引入封装好的请求方法
import { getFilePDF } from '@/api/downRequest'
let params= {
// 需要搜索的字段
};
getFilePDF('请求的后端接口',params).then(res => {
// 表格 application/xlsx,压缩包为 application/zip等,这里是pdf类型
const pdfUrl = window.URL.createObjectURL(new Blob([res.data], { type: "application/pdf" }));
const fileName = "PDF文件下载"; // 下载文件的名字
if (typeof window.navigator.msSaveBlob !== "undefined") {
window.navigator.msSaveBlob(pdfUrl, filename);
} else {
const link = document.createElement('a');
link.href = pdfUrl;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link) //下载完成移除元素
window.URL.revokeObjectURL(pdfUrl) //释放掉blob对象
}
})
最终展示效果:
![](https://img.haomeiwen.com/i24939088/4d955f25b8a3c43d.png)
网友评论