在項目中遇到一個需求,須要導出文件,以往的作法是使用location.href跳轉,剩下的就直接交給後端就行了,但由於認證方式使用的是jwt,因此須要在請求的時候添加自定義http請求頭,傳統的方式再也不適用。javascript
responseType: 'arraybuffer'
複製代碼
指定返回值類型java
將返回的二進制數據轉爲Bolb對象ios
將bolb對象轉爲 DataURLaxios
利用a標籤下載文件後端
廢話很少說直接上代碼bash
const requestUse = (config) => {
if (!config) {
// eslint-disable-next-line
config = {
headers: {
Authorization: getToken(),
},
};
} else if (config.isLogin) {
return config;
} else if (!config.headers.Authorization) {
config.headers.Authorization = getToken();
}
return config;
};
request = axios.create({
baseURL: '',
});
request.interceptors.request.use(requestUse);
request.get(url, { params, responseType: 'arraybuffer', }).then((resp) => {
const disposition = resp.headers['content-disposition'];
const fileName = decodeURI(disposition.substring(disposition.indexOf('fileName=') + 9, disposition.length));
let blob;
if (navigator.msSaveBlob){
// IE 10+
blob = navigator.msSaveBlob(new Blob([resp.data], { type: resp.headers['content-type'] }), fileName);
} else {
blob = new Blob([resp.data], { type: resp.headers['content-type'] });
}
console.log(resp, blob);
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = (e) => {
const a = document.createElement('a');
a.download = fileName;
// 後端設置的文件名稱在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"20181211191944.zip\"",
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
});
複製代碼