簡體   English   中英

如何使用 fetch API 在 javascript 中下載具有多個塊的單個文件

[英]How to download single file with multiple chunks in javascript using fetch API

我在我的 React 應用程序中使用fetch API 從 URL 下載文件。 每個 URL 提供一個塊作為響應。 當文件只有一個塊時,我可以使用response.blob()下載文件。 但是,如果單個文件有多個塊,我必須從 n 個不同的 url 中獲取塊,比如 url1,url2,..so。 我如何組合他們的響應以生成單個 blob 並下載文件。

以下是僅使用一個塊(從 url-1 獲取)下載文件的代碼。

let downloadUrl = `https://url-1`;
      fetch(downloadUrl, {
        method: 'GET'
      })
        .then(
          (res: any) => {
            if (res.ok && res.status === 200) {
              //File response loaded
            } else {
              return null;
            }
            return res.blob();
          },
          error => {
            // error in downloading
          }
        )
        .then(fileData => {
          if (fileData) {
            let url = window.URL.createObjectURL(fileData);
            let a = document.createElement('a');
            a.href = url;
            a.download = file.fileName;
            a.click();
          }
        });

我可以在 fetch API 中發出多個請求並使用Promise.all(responseArr) 但是如何將他們的響應組合成單個 blob 響應?

您可以使用fetch()單個塊,然后使用.arrayBuffer()將每個響應作為數組緩沖區。

然后,您可以使用Blob(array, options)構造函數創建一個新的 blob,其中包含您剛剛下載的所有數組緩沖區。

例子:

// fetch chunks from somewhere
let urls = ["http://foo.bar/chunk/1", "http://foo.bar/chunk/2"];
let chunkPromises = urls.map(url => {
  return fetch(url).then(res => {
    return res.arrayBuffer();
  });
});

Promise.all(chunkPromises).then(chunks => {
  // combine chunks into a single blob
  let blob = new Blob(chunks, {
    // Optional: specify the MIME Type of your file here
    type: "text/plain" 
  });

  // download the blob
  let url = window.URL.createObjectURL(blob);
  let a = document.createElement('a');
  a.href = url;
  a.download = "Filename.txt";
  a.click();
});

我會遍歷 URL 以按順序下載塊並在下載時組合它們

try{
    var urls = ['https://url-1','https://url-2.0','https://url-3.1415']
    var fullFile = new Blob();
    for (let x = 0; x < urls.length; x++){
        await fetch(urls[x]).then((res) => {
            if (!res.ok || res.status !== 200) {
                throw('Download failed');
            }
            return res.blob();
        }).then(data => fullFile = new Blob([fullFile, data]));
    }
    let url = window.URL.createObjectURL(fullFile);
    let a = document.createElement('a');
    a.href = url;
    a.download = file.fileName;
    a.click();
} 
catch(e){console.log(e)};

暫無
暫無

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

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