【问题标题】:How to download .zip file that i recieve from a HTTP response (axios PUT request)如何下载我从 HTTP 响应(axios PUT 请求)收到的 .zip 文件
【发布时间】:2022-02-03 19:05:59
【问题描述】:

所以 API 的响应包含 data 属性,它应该包含我需要的 .zip 文件。它是用我不明白的格式写的。

格式:

我尝试使用 .blob() 在 Stackoverflow 上的类似问题中引用,但它似乎不起作用。

理想的解决方案是:当客户端按下按钮时,应该提示他在本地下载所述.zip文件(来自HTTP响应的那个)。我用的是axios,请求类型是PUT

到目前为止我的代码示例:

  const exportCards = () => {
    axios
      .put(url, {
        ids: ids,
      })
      .then((res) => {
        return res.data.blob();
      })
      .then((blob) => {
        var file = window.URL.createObjectURL(blob);
        window.location.assign(file);
      })
      .catch((e) => console.log(e));
  };

【问题讨论】:

  • 后端正在向您发送不良数据。看起来服务器代码将 zip 文件读入 Node Buffer,然后使用 Buffer.toString() 将其序列化为 JSON。这会破坏数据,因为这些字符显示。它应该使用Buffer.toJSON()

标签: javascript node.js reactjs http


【解决方案1】:

a 标签有download 属性,在.then 你可以尝试类似的东西

const url = new Blob([response.data],{type:'application/zip'});
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.zip'); //set download attribute to link
document.body.appendChild(link);
link.click(); // this will download file.zip

【讨论】:

  • 我试过了,它不起作用 Gurika
猜你喜欢
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 2019-01-02
相关资源
最近更新 更多