Fetch Api Download Progress Indicator?
I am trying to capture the download progress of a Fetch request and use that to change the width of a progress bar. I looked at ProgressEvent.lengthComputable as a potential soluti
Solution 1:
without checking for errors (as in try/catch etc...)
const elStatus = document.getElementById('status');
functionstatus(text) {
elStatus.innerHTML = text;
}
const elProgress = document.getElementById('progress');
functionprogress({loaded, total}) {
elProgress.innerHTML = Math.round(loaded/total*100)+'%';
}
asyncfunctionmain() {
status('downloading with fetch()...');
const response = awaitfetch('https://fetch-progress.anthum.com/30kbps/images/sunrise-baseline.jpg');
const contentLength = response.headers.get('content-length');
const total = parseInt(contentLength, 10);
let loaded = 0;
const res = newResponse(newReadableStream({
asyncstart(controller) {
const reader = response.body.getReader();
for (;;) {
const {done, value} = await reader.read();
if (done) break;
loaded += value.byteLength;
progress({loaded, total})
controller.enqueue(value);
}
controller.close();
},
}));
const blob = await res.blob();
status('download completed')
document.getElementById('img').src = URL.createObjectURL(blob);
}
main();
<divid="status"> </div><h1id="progress"> </h1><imgid="img" />
adapted from here
Solution 2:
you can use axios instead
import axios from'axios'exportasyncfunctionuploadFile(file, cb) {
const url = `//127.0.0.1:4000/profile`try {
let formData = newFormData()
formData.append("avatar", file)
const data = await axios.post(url, formData, {
onUploadProgress: (progressEvent) => {
console.log(progressEvent)
if (progressEvent.lengthComputable) {
let percentComplete = progressEvent.loaded / progressEvent.total;
if (cb) {
cb(percentComplete)
}
}
}
})
return data
} catch (error) {
console.error(error)
}
}
Post a Comment for "Fetch Api Download Progress Indicator?"