I created one test like this:
async function testDownload()
{
try{
var urls = ['https://localhost:54373/analyzer/test1','https://localhost:54373/analyzer/test2']
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 = "WTF.ini";
a.click();
}
catch(e){console.log(e)};
}
The problem is: This created the download link after I received the result from urls. So I get the instant file https://prnt.sc/-zSK3Y7QLIVT
My question is: How i make this with percent for download? Like this: https://prnt.sc/sdvxMc83qqeS
You should divide in known size chunks (e.x 4kb each) and knowning the total file size and the chunk size you can compute the percentage downloaded each time a chunk is finished.
function PercentageCalculatorFactory(totalFileSizeInBytes){
var totalDownloaded = 0;
const chunkSize = 4096;
return function onChunkDownload(){
totalDownloaded ++;
var sizeDownloaded = totalDownloaded * chunkSize;
return sizeDownloaded / totalFileSize * 100;
}
}
//usage
var percCalculator = PercentageCalculatorFactory(10000);
//get the file size using an api that serves some metadata about the file, in this case the size but the name might be needed etc.
async function testDownload()
{
try{
var urls = ['https://localhost:54373/analyzer/test1','https://localhost:54373/analyzer/test2']
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');
}
var newPercentage = percCalculator();
//do something with percentage
console.log( newPercetage );
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 = "WTF.ini";
a.click();
}
catch(e){console.log(e)};
}