話不多少,直奔主題:
axios.post(url, file, {
headers: {
"Content-Type": "multipart/form-data"
},
responseType: 'blob',
}).then(res => {
const content = res.data;
const blob = new Blob([content]); //構造一個blob對象來處理數據
const fileName = `${name}.xls`;
//對於<a>標籤,只有 Firefox 和 Chrome(內核) 支持 download 屬性
//IE10以上支持blob但是依然不支持download
if ("download" in document.createElement("a")) {
//支持a標籤download的瀏覽器
const link = document.createElement("a"); //創建a標籤
link.download = fileName; //a標籤添加屬性
link.style.display = "none";
link.href = URL.createObjectURL(blob);
document.body.appendChild(link);
link.click(); //執行下載
URL.revokeObjectURL(link.href); //釋放url
document.body.removeChild(link); //釋放標籤
} else {
//其他瀏覽器
navigator.msSaveBlob(blob, fileName);
}
});
注意:
1、由於我的需求是上傳文件後直接下載,所以"Content-Type"設置爲"multipart/form-data",可根據自己需要修改
2、需要標明數據返會格式即responseType: 'blob',否則即使拿到流也不會下載
3、由於我的res會有code,data,message所以content取值爲res.data