简体   繁体   English

如何使用 axios 下载文件?

[英]How to download a file using axios?

I am using Vue js to make a post request to a backend API.我正在使用 Vue js 向后端 API 发出发布请求。 The response data should be downloaded into a zip file.响应数据应下载到 zip 文件中。 Though the file downloads as a zip file, I get an error when I try to open the file.虽然文件下载为 zip 文件,但当我尝试打开文件时出现错误。 Error message: Windows cannot open the folder.错误信息:Windows 无法打开文件夹。 The compressed (zipped) folder "........\test.zip" is invalid.压缩(压缩)文件夹“........\test.zip”无效。

Here is my vue code这是我的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();
    });

Update更新

I used this code我用了这段代码

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;
        }

to convert it to a UintArray.将其转换为 UintArray。 I received another error 'DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.'我收到另一个错误“DOMException:无法在“窗口”上执行“atob”:要解码的字符串未正确编码。

You can use FileSaver :您可以使用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