后端返回文件流,前端实现下载功能
目录
后端返回文件流,前端实现下载功能
1,接口设置 responseType: “blob”
export function sopExportPDF(id) {
return request({
url: "/tb/procedure/export/pdf/" + id,
responseType: "blob",
method: "get",
});
}
2. 项目安装downloadjs
npm install downloadjs
3.需要的页面引入模块
import download from "downloadjs";
4.在接口函数中创建blob对象,并调用download方法
// 导出单个sop
async ExportPDF(id, name) {
let res = await sopExportPDF(id);
let blob = new Blob([res], { type: "applictation/pdf" });
download(blob, name + ".pdf", "application/pdf");
// let href = URL.createObjectURL(blob);
// let a = document.createElement("a");
// a.style.display = "none";
// a.href = href; // 指定下载链接
// a.download = name + ".pdf"; //指定下载文件名
// a.click(); //触发下载
// URL.revokeObjectURL(a.href); //释放URL对象
},
注意:文件下载后无法打开或者损坏请检查接口api是否添加: responseType: “blob”
后端返回文件流获取文件名称
1.在使用的文件中引入axios并配置
import axios from "axios";
axios.defaults.headers["Authorization"] = "Bearer " + getToken();
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
2.在函数中使用axios发送接口
// 导出单个sop
ExportPDF(id, name) {
axios({
url: process.env.VUE_APP_BASE_API + "/tb/procedure/export/pdf/" + id,
responseType: "blob",
method: "get",
}).then((response) => {
console.log(response);
let dispositionStr = response.headers["content-disposition"];
// 获取文件名
let dispositionArr = dispositionStr.split(";");
// 获取文件名
let fileName = decodeURIComponent(dispositionArr[1]);
fileName = fileName.split("=")[1];
let blob = new Blob([response.data], { type: "applictation/pdf" });
download(blob, fileName, "application/pdf");
});
注意:后端一定要配置content-disposition响应头!!!