分享一個axios請求接口,拿到二進制數據后下載zip文件的方法:
export const downloadZip = (url, method = 'post', data, options = {contentType:"multipart/form-data",responseType:'blob'}, name='未命名') => {
let loadingInstance = Loading.service({ fullscreen: true, text:'下載中,請稍等......' });
let params = {};
if (method.toLowerCase() === 'get') { // 根據不同情況處理參數
params = {params: {...data}}
} else if (options.contentType === 'multipart/form-data') {
params = {data}
} else {
params = {data: {...data}}
}
axios({
url,
method,
responseType: options.responseType,
...params,
headers: {
TOKEN: getToken(), // 此處根據項目設定
"Content-Type": options.contentType
}
}).then((response) => {
const blob = new Blob([response.data], { type: "application/zip" }); // 此處type可以作為參數傳入
if (blob.size < 500) {
Message.error('暫無數據')
loadingInstance.close()
return
}
const url = window.URL.createObjectURL(blob);
const LINK = document.createElement('a');
LINK.href = url;
LINK.setAttribute('download', name);
document.body.appendChild(LINK);
LINK.click();
LINK.remove(); // 釋放內存
URL.revokeObjectURL(url)
setTimeout(()=> {
loadingInstance.close()
}, 2000)
}).catch(err=>{
loadingInstance.close()
});
}
以上axios().then().catch()鏈式寫法 可以 用 async await 改寫,很簡單這里就先不做修改了