vue项目使用axiox封装http请求,需求是实现下载功能
为了安全要携带用户Token以及需要走封装的拦截器,所以只能使用封装的http请求来下载
查了一下需要用Blob流来下载
以下是我的实现方案(如有不足,欢迎大佬指正!):
下载按钮执行:
/** 导出按钮操作 */
async answerFileDownloadFun(item) {
try {
let res = await answerFileDownload(item.questionNaireId, item.anwserId);
debugger;
if (res.data.type === "application/octet-stream") {
// 获取http头部的文件名信息,若无需重命名文件,将下面这行删去
const fileName = res.headers["content-disposition"].split("=")[1];
/* 兼容ie内核,360浏览器的兼容模式 */
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
const blob = new Blob([res.data], {
type: "application/zip"
});
window.navigator.msSaveOrOpenBlob(
blob,
decodeURIComponent(fileName)
);
} else {
/* 火狐谷歌的文件下载方式 */
const blob = new Blob([res.data], {
type: "application/zip"
});
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a"); // 创建a标签
link.href = url;
link.download = decodeURIComponent(fileName); // 文件重命名,若无需重命名,将该行删去
link.click();
URL.revokeObjectURL(url); // 释放内存
}
} else {
const reader = new FileReader();
reader.onload = function(event) {
const msg = JSON.parse(reader.result).data;
};
reader.readAsText(res.data);
}
} catch (error) {
console.error(error);
}
},
api.js设置请求路径:
// 下载附件
export function answerFileDownload(questionNaireId,anwserIds) {
return request({
url: '/questionnaire/questionNaireAnswer/answerFileDownload/' + questionNaireId + '/' + anwserIds,
method: 'get',
noFetchTime:true//设置超长超时时间
})
}
封装请求request.js(设置超时时间及下载类型):
if (config.noFetchTime) {
config.timeout = 200000000000000000
config.responseType = "blob"
}
第一次发布文章,请大家多多指正