代码的请求思路:请求后端接口,返还blob文件。
qs.stringify 是把一个参数对象格式化为一个字符串。
axios({
method: "get",
url: `/api/list/download?${qs.stringify(params)}`,
headers: {
Authorization: "Bearer " + accessToken,
},
responseType: "blob",
}).then(()=>{
})
返还文件下载思路:
判断文件返还的格式类型,使用前端a链接的方式进行前端单个文件下载功能的实现。
import { ElMessage } from "element-plus";
export function readFileDownload(data, msg) {
var res = data;
if (
res.type === "application/json" ||
res.type === "application/json;charset=UTF-8"
) {
// 失败的时候,注意ie兼容问题
let fileReader = new FileReader();
fileReader.onload = function () {
let jsonData = JSON.parse(this.result); // this.result是根据event,读取文件后打印的 event.target.reslut
if (jsonData.data === null && jsonData.status === 400) {
ElMessage({
message : jsonData.message || "Error",
type: "error",
duration: 5 * 1000,
});
}
};
fileReader.readAsText(res);
}
if (
res.type === "application/octet-stream" ||
res.type === "application/vnd.ms-excel" ||
res.type === "application/vnd.ms-exce" ||
res.type === "application/vnd.ms-excel;charset=UTF-8" ||
res.type ===
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
) {
console.log("success..."); // 成功,注意ie兼容问题
const blob = new Blob([res], {
type: "application/vnd.ms-excel;charset=utf-8",
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, msg);
} else {
console.log(blob);
const url = window.URL.createObjectURL(blob);
console.log(url);
const aLink = document.createElement("a");
aLink.style.display = "none";
aLink.href = url;
aLink.setAttribute("download", msg);
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
window.URL.revokeObjectURL(url);
}
}
}