簡體   English   中英

如何使用 axios 下載文件?

[英]How to download a file using axios?

我正在使用 Vue js 向后端 API 發出發布請求。 響應數據應下載到 zip 文件中。 雖然文件下載為 zip 文件,但當我嘗試打開文件時出現錯誤。 錯誤信息:Windows 無法打開文件夾。 壓縮(壓縮)文件夾“........\test.zip”無效。

這是我的vue代碼

let config = {
    Headers: {
      "Content-Type": "multipart/form-data",
      responseType: "blob",
    },
  };
  axios
    .post(
      `http://localhost:5050/generator`,
      this.forms,
      config
    )
    .then((response) => {
      const zipName = "test";
      this.forms = {
        productName: "",
        companyName: "",
      
      };
      const url = window.URL.createObjectURL(
        new Blob([response.data], { type: "application/zip" })
      );
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", zipName + ".zip"); 
      document.body.appendChild(link);
      link.click();
    });

更新

我用了這段代碼

function _base64ToArrayBuffer(base64) {
          var binary_string = window.atob(base64);
          var len = binary_string.length;
          var bytes = new Uint8Array(len);
          for (var i = 0; i < len; i++) {
            bytes[i] = binary_string.charCodeAt(i);
          }
          return bytes.buffer;
        }

將其轉換為 UintArray。 我收到另一個錯誤“DOMException:無法在“窗口”上執行“atob”:要解碼的字符串未正確編碼。

您可以使用FileSaver

import SaveAs from "file-saver";

.....
.then((response) => 
{
  ....
  saveAs(new Blob([response.data], { type: 'application/octet-stream' }), response.filename, { autoBOM: false });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM