简体   繁体   中英

How to transfer file chunks for large file download and reconstruct it in javascript?

I need to download large files using files chunks for which JAVA spring server is developed and files are recived at UI via REST api. Looking for solution to join all chunks in javascript

i am not sure about your requirement but hope this will help you

first you need to fetch the file using a fetch call inside a async function

response = await fetch(url);

then after that you will be able to get a reader from the response const reader = response.body.getReader();

you can track the fetch by measuring the progress for that store the total file size

const contentLength = +response.headers.get('Content-Length');

in ordre to track the recieved bytes let receivedLength = 0;

to store the chunks recieved

let chunks = []; // array of received binary chunks (comprises the body)

after that do a while loop which will run endlessly

while(true) {
          const {done, value} = await reader.read();

          if (done) {
            break;
          }

          chunks.push(value);
          receivedLength += value.length;
            
          let compleated = Math.round(receivedLength/contentLength*100);

          console.log(`Received ${receivedLength} of ${contentLength}`)
        }

 after the while loop has broken you can check if the transfer is fully completed or not

then you can create a blob from the array which we stored our chunks of data

let blob = new Blob(chunks);

then you can use this blob

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM