1. 程式人生 > 實用技巧 >匯出檔案,responseType設定了blob,實際返回了JSON格式的錯誤資訊的處理方式

匯出檔案,responseType設定了blob,實際返回了JSON格式的錯誤資訊的處理方式

需求:匯出檔案

問題描述:由於後臺直接返回的檔案流,在請求下載的方法中將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)。