需求:導出文件
問題描述:由於后台直接返回的文件流,在請求下載的方法中將XHR 的 responseType 指定為 blob 或者 arraybuffer。但並不是每次的操作都是成功的,所以在接口錯誤時后台返回的就是不是二進制流格式了。因此這里需要獲取到后台反饋的錯誤信息進行用戶提示。
這時后台返回的數據類型就是這樣的:
而接口返回的是json的數據信息{“msg”: "導出失敗", code: 1007}
解決代碼示例:
getFiles(_path, query) { axios({ method: 'get', // 請求方式 headers: { 'Content-Type': 'application/octet-stream', 'token': store.getters.token }, url: _path, // 請求路徑 params: query, responseType: 'blob' }).then(res => { const data = res.data; if (res.data.type == 'application/json') {
// json信息展示 this.handlerResponseError(data); } else { // 下載文件流 const filename = this.getCaption(res.headers['content-disposition']); const blob = new Blob([res.data], { type: 'application/octet-stream' }); const objectUrl = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = objectUrl; link.setAttribute('download', filename); document.body.appendChild(link); link.click();// 點擊 document.body.removeChild(link); // 下載完成移除元素 window.URL.revokeObjectURL(URL); // 釋放掉blob對象 } }).catch((err) => { console.log(err, 'err'); }); }, handlerResponseError(data) { const _this = this; const fileReader = new FileReader(); fileReader.onload = function() { try { const jsonData = JSON.parse(fileReader.result); // 說明是普通對象數據,后台轉換失敗 console.log('后台返回的信息',jsonData.msg); // dosomething…… } catch (err) { // 解析成對象失敗,說明是正常的文件流 console.log('success...'); } }; fileReader.readAsText(data); },
PS:MDN官方解釋:Blob 對象表示一個不可變、原始數據的類文件對象。Blob 表示的不一定是JavaScript原生格式的數據(https://developer.mozilla.org/zh-CN/docs/Web/API/Blob)。