以下是一個拿到流數(shù)據(jù)后的下載操作代碼實(shí)現(xiàn)
// download.js
// 處理下載流
export const download = (content, fileName) => {
const blob = new Blob([content]); // 創(chuàng)建一個類文件對象:Blob 對象表示一個不可變的爵嗅、原始數(shù)據(jù)的類文件對象
// URL.createObjectURL(object) 表示生成一個 File 對象或 Blob 對象
const url = window.URL.createObjectURL(blob);
const dom = document.createElement("a"); // 設(shè)置一個隱藏的 a 標(biāo)簽,href 為輸出流硬梁,設(shè)置 download
dom.style.display = "none";
dom.href = url;
dom.setAttribute("download", fileName); // 指示瀏覽器下載 url,而不是導(dǎo)航到它劈猪;因此將提示用戶將其保存為本地文件
document.body.appendChild(dom);
dom.click();
document.body.removeChild(dom); // 下載完成移除元素
window.URL.revokeObjectURL(url); // 釋放掉 blob 對象
};
/**
* 獲取http響應(yīng)的文件名
* @param {*} str http響應(yīng)header中content-disposition字段
* @returns
*/
export const getFileName = (str) => {
const arr = str.split(";");
// filename*=
let temp = arr.find((e) => e.startsWith("filename*="));
if (temp) {
// 默認(rèn)utf-8模式
const index = temp.lastIndexOf("'");
return decodeURIComponent(temp.slice(index + 1));
}
// filename=
temp = arr.find((e) => e.startsWith("filename="));
if (temp) {
return temp.replace("filename=", "");
}
throw Error(
"未在響應(yīng)頭獲取到文件名(請檢查響應(yīng)頭字段大小寫)碎赢,且默認(rèn)自定義文件名未傳!!"
);
};
/**
* 處理下載流
* @param {*} response 完整的http響應(yīng)
* @param {*} fileName 自定義的文件名(如果沒傳從response中拿到)
*/
export const downloadV2 = (response, fileName = false) => {
const name = fileName ? fileName : response.headers["content-disposition"];
let filename = "";
try {
filename = getFileName(name);
} catch (error) {
console.error(error);
return;
}
const blob = new Blob([response.data]); // 創(chuàng)建一個類文件對象:Blob 對象表示一個不可變的凉袱、原始數(shù)據(jù)的類文件對象
// URL.createObjectURL(object) 表示生成一個 File 對象或 Blob 對象
const url = window.URL.createObjectURL(blob);
const dom = document.createElement("a"); // 設(shè)置一個隱藏的 a 標(biāo)簽傲宜,href 為輸出流运杭,設(shè)置 download
dom.style.display = "none";
dom.href = url;
dom.setAttribute("download", filename); // 指示瀏覽器下載 url,而不是導(dǎo)航到它;因此將提示用戶將其保存為本地文件
document.body.appendChild(dom);
dom.click();
document.body.removeChild(dom); // 下載完成移除元素
window.URL.revokeObjectURL(url); // 釋放掉 blob 對象
};
axios遇到流下載異常返回JSON時的處理
// 如果是下載文件流報錯函卒,轉(zhuǎn)換錯誤信息為json響應(yīng)
if (responseType === "blob") {
let resBlob = res.data;
return new Promise(function (resolve) {
let reader = new FileReader();
reader.readAsText(resBlob, "utf-8");
reader.onload = () => {
let ress = JSON.parse(reader.result);
if (ress.code !== 0) {
// 提示錯誤的信息
Message({
showClose: true,
message: ress.msg,
type: "error",
});
return resolve(ress);
}
};
});
}