重點(diǎn):調(diào)用接口時(shí),一定要配置 responseType 的值為 blob,不然獲取的文件流,不會(huì)轉(zhuǎn)義成 blob 類型的文件。文章來源地址http://www.zghlxwxcb.cn/news/detail-777293.html
1. 接口返回文件流
// BLOB (binary large object)----二進(jìn)制大對(duì)象,是一個(gè)可以存儲(chǔ)二進(jìn)制文件的容器
// 下載接口:重點(diǎn)responseType: "blob"
// 返回體 res blob 文件流
function downloadFile(params) {
return api({
url: "/download/file",
method: "get",
params,
responseType: "blob",
});
}
2. 文件流下載:簡單版
/**
* 下載函數(shù)
* @param {string} data - 后端獲取的文件流
* @param {string} name - 文件名
*/
function downloadFile(data, name) {
const blob = new Blob([data]);
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.style.display = "none";
a.click();
document.body.removeChild(a);
}
3. 文件流下載:豪華版
/**
* 全面優(yōu)化下載函數(shù)
*/
function downloadFile(res) {
// 判斷是否接口調(diào)用是否正常返回文件流
const r = new FileReader();
r.readAsText(res.data);
r.onload = () => {
try {
// 報(bào)錯(cuò),未返回
const resData = JSON.parse(r.result);
} catch (err) {
// 正常,開始轉(zhuǎn)換文件流
// 正常情況,瀏覽器不返回字段為 content-disposition 的請(qǐng)求頭,
// 需要后端特殊聲明下,才拿得到,response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
const name = res.headers["content-disposition"];
const fileName = name.split("=")[1];
// 解碼
filename = decodeURIComponent(fileName);
// 兼容ie11
if (window.navigator.msSaveOrOpenBlob) {
try {
const blobObject = new Blob([res.data]);
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
} catch (e) {
console.log(e);
}
return;
}
// a標(biāo)簽實(shí)現(xiàn)下載
const url = window.URL.createObjectURL(new Blob([res.data]));
const a = document.createElement("a");
a.style.display = "none";
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
resolve(fileName);
document.body.removeChild(a);
}
};
}
文章來源:http://www.zghlxwxcb.cn/news/detail-777293.html
到了這里,關(guān)于前端 JS 經(jīng)典:文件流下載的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!