簡體   English   中英

如何下載我從 HTTP 響應(axios PUT 請求)收到的 .zip 文件

[英]How to download .zip file that i recieve from a HTTP response (axios PUT request)

因此 API 的響應包含data屬性,該屬性應包含我需要的 .zip 文件。 它以我不理解的格式編寫。

格式: 在此處輸入圖像描述

我嘗試使用.blob()作為 Stackoverflow 上類似問題中引用的內容,但它似乎不起作用。

理想的解決方案是這樣的:當客戶端按下按鈕時,應該提示他在本地下載 said.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));
  };

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

I would suggest fetch over axios in concern of zip file because sometimes the response in axios request is not accurate and you might fall into currupted zip file while downloading, the best might be using a package called file-saver and fetch. 我發布這個答案是為了幫助開發人員抓住這個概念,代碼是在 React 中測試的。

package文件保護程序https://www.npmjs.com/package/file-saver

現在根據您在反應中的選擇制作任何 function,我假設功能組件,因此將根據功能組件語法編寫方法。 請注意,在使用 saveAs function 之前,您需要從已安裝的 package 文件保護程序中導入。

import { saveAs } from 'file-saver';

const downloadZipFileFromLaravel=()=>{
 fetch(`your url`)
           
                    .then(res => res.blob())
                    .then(blob => saveAs(blob, 'Auto Photos.zip')) // saveAs is a function from the file-saver package. 
              .catch((err) => {
                console.log(err.message);
              });
}

最后,您需要將 function 與 onClick 的按鈕連接起來。 例子

<button onClick={()=>downloadZipFileFromLaravel()}> </button>

注意:在純 javascript 中使用文件保護程序,您可以查看: 如何使用 filesaver.js

有關更多信息,您可以查看以下討論:參考: https://github.com/eligrey/FileSaver.js/issues/156

我想要什么:

  • 將任何格式的文件從后端發送到前端

我的工具:

  • axios,快遞,另存為

我面臨的問題:

沒有什么能幫到我,可能是因為我做錯了什么。 但這是我想出的一個簡單快捷的解決方案:

//BE
const filename = "my-file-name.json";

const zip = new AdmZip();
zip.addFile(filename, body);
const content = zip.toBuffer();

res.set({
            "Content-Length": Buffer.byteLength(content), //I'm not sure if this is necessary, but it's better to let it be :-)
            "Content-Type": "text/plain",
            "Content-Disposition": `attachment; filename=${filename}.${format}`,
          });
res.status(200).send(content.toString("hex")); //my solution to the problem

//FE
const { headers, data } = await axios.post(myEndpoint);
const headerLine = headers["content-disposition"];
const filename = headerLine.replace(/[\w; ]+filename=/g, "");

const content = Buffer.from(data, "hex");
const blob = new Blob([content], { type: "application/zip" });
saveAs(blob, filename); //file-saver npm package

您的問題是您沒有在PUT請求中明確指定響應類型。 這應該工作:

const exportCards = () => {
  axios
    .put(url, {
      ids: ids,
    }, {
      responseType: 'blob'
    })
    .then((res) => { // Now 'res.data' is Blob, not a string
      var file = window.URL.createObjectURL(res.data);
      window.location.assign(file);
    })
    .catch((e) => console.log(e));
};

在此處輸入圖像描述

暫無
暫無

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

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