You dont have to read the code, what is happening is a file is being uploaded 1000 bytes at a time. And to ensure that we send the bytes in order we are using await
. What if I wanted to use .then()
, it seems hard as there is a loop around the fetch call.
JavaScript
x
30
30
1
const fileReader = new FileReader();
2
const theFile = f.files[0];
3
fileReader.onload = async (ev) => {
4
const CHUNK_SIZE = 5000;
5
const chunkCount = ev.target.result.byteLength / CHUNK_SIZE;
6
7
console.log("Read successfully");
8
const fileName = Math.random() * 1000 + theFile.name;
9
for (let chunkId = 0; chunkId < chunkCount + 1; chunkId++) {
10
const chunk = ev.target.result.slice(
11
chunkId * CHUNK_SIZE,
12
chunkId * CHUNK_SIZE + CHUNK_SIZE
13
);
14
await fetch("http://localhost:8080/upload", {
15
method: "POST",
16
headers: {
17
"content-type": "application/octet-stream",
18
"content-length": chunk.length,
19
"file-name": fileName,
20
},
21
body: chunk,
22
});
23
divOutput.textContent =
24
Math.round((chunkId * 100) / chunkCount, 0) + "%";
25
}
26
console.log(ev.target.result.byteLength);
27
};
28
fileReader.readAsArrayBuffer(theFile);
29
});
30
Advertisement
Answer
Here is the same functionality without await
. It replaces the for
loop:
JavaScript
1
22
22
1
const uploadChunk = (chunkId = 0) => {
2
const chunk = ev.target.result.slice(
3
chunkId * CHUNK_SIZE,
4
chunkId * CHUNK_SIZE + CHUNK_SIZE
5
);
6
fetch("http://localhost:8080/upload", {
7
method: "POST",
8
headers: {
9
"content-type": "application/octet-stream",
10
"content-length": chunk.length,
11
"file-name": fileName,
12
},
13
body: chunk,
14
}).then(() => {
15
divOutput.textContent =
16
Math.round((chunkId * 100) / chunkCount, 0) + "%";
17
(chunkId <= chunkCount) && uploadChunk(chunkId + 1);
18
});
19
}
20
21
uploadChunk();
22