js下載檔案流,提示檔案損壞問題
阿新 • • 發佈:2021-02-04
技術標籤:jsjavascript
記錄一下前端下載後端返回的檔案流,提示檔案損壞問題。
const blob = new Blob([content.data], {
// type是需要對應的檔案型別
type:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const fileName = "檔名.xlsx";
if ("download" in document.createElement("a")) {
// // 非IE下載
const elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
console.log(blob, elink.href, "href", elink);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 釋放URL 物件
document.body.removeChild(elink);
} else {
// IE10+下載
navigator.msSaveBlob(blob, fileName) ;
}
正常情況下,這樣下載就OK了。然後發現提示檔案格式或副檔名無效。
後面跟後端聯調中發現,後端返回的request裡面加了
然後前端axios,也需要加responseType: “blob”,這樣才能正常下載檔案流。