1. 程式人生 > 其它 >使用post介面進行大批量匯出檔案

使用post介面進行大批量匯出檔案

在工作中,使用get方法匯出檔案會遇到一些問題:url長度限制,傳入id量大且載入速度慢,所以拋棄以前的請求下載方式,使用post介面進行請求下載!

  本次的匯出檔案為excel檔案,其他檔案未嘗試!

以前的方法,使用get介面:

import { getToken } from "@/util/auth";

exportFile(){
    let url_str = `/api/exportFile?Blade-Auth=${getToken()}&ids=${
        this.ids
     }`;
    console.log("url_str", url_str);
    this.$downFile(url_str, "財務匯出報告.xlsx");
    this.$message({
        type: "success",
        message: "匯出成功!",
     });
};

現在的方法,使用post介面:

介面js如下:(必須寫上 responseType: "blob" ,否則下載的檔案會亂碼)

export const exportFile = (ids) => request({
    url: '/api/exportFile',
    method: 'post',
    data: ids,
    responseType: "blob"
})

頁面vue程式碼如下:

import { exportFile } from "@/api/axiosInfo.js";

exportFile(){
    exportFile({ ids: this.ids }).then((res) => {
          // 大批量匯出
          var blob = new Blob([res.data], {
            //這個裡面的data 的二進位制檔案 建立一個檔案物件
            type: "application/vnd.ms-excel;charset=utf-8",
          });
          var downloadElement = document.createElement("a"); //建立一個a 虛擬標籤
          var href = window.URL.createObjectURL(blob); // 建立下載的連結
          downloadElement.href = href;
          downloadElement.download =
            decodeURI(
              res.headers["content-disposition"].split("filename=")[1]
            ) || ""; // 下載後文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 點選下載
          document.body.removeChild(downloadElement); // 下載完成移除元素
          window.URL.revokeObjectURL(href); // 釋放掉blob物件
};

該方法來源於:

js post 請求介面下載檔案 作者:義美-小義