axios前後端分離下載檔案

txl1123發表於2018-10-17

寫vue專案用的axios庫,在處理下載檔案的時候,發現後端返回的是檔案流,無法直接下載,只能用a標籤處理,但是對於有鑑權的下載,a標籤顯然是不合適的了。於是乎就查閱各種資料各種鼓搗終於搞出來了

axios請求下載

請求下載的時候設定responseType為blob,例如:

export function apiDownloadFiles(fielId) {
  return axios({
    url: `/document/${fielId}`,
    method: 'get',
    responseType: 'blob'
  })
}
複製程式碼

這樣請求就會走axios攔截器裡配置的方法,你就可以給下載新增請求頭token了

請求後獲取到的檔案流如何下載到本地呢?

後端返回了的檔案流是這樣的

axios前後端分離下載檔案
這個時候要怎麼處理才能變成檔案呢?

apiDownloadFiles(file.id).then(res => {
          if (res.data.type === "application/json") {
            this.$message({
              type: "error",
              message: "下載失敗,檔案不存在或許可權不足"
            });
          } else {
            let blob = new Blob([res.data]);
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, file.fileName);
            } else {
              let link = document.createElement("a");
              let evt = document.createEvent("HTMLEvents");
              evt.initEvent("click", false, false);
              link.href = URL.createObjectURL(blob); 
              link.download = file.fileName;
              link.style.display = "none";
              document.body.appendChild(link);
              link.click();
              window.URL.revokeObjectURL(link.href);
            }
          }
        });
複製程式碼

模擬a標籤點選,成功下載檔案。

相關文章