Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Move file uploads to xhr as r2 does not support http2
  • Loading branch information
regalijan committed Mar 26, 2024
1 parent 30b3845 commit 2411714
Showing 1 changed file with 24 additions and 45 deletions.
69 changes: 24 additions & 45 deletions app/routes/report.tsx
Expand Up @@ -185,53 +185,32 @@ export default function () {

setUploading(true);

for (let i = 0; i < upload_urls.length; i++) {
const reader = files[i].stream().getReader();

try {
const uploadReq = await fetch(upload_urls[i], {
body: supportsRequestStreams
? new ReadableStream({
async pull(controller) {
const chunk = await reader.read();

if (chunk.done) {
controller.close();

if (i === upload_urls.length - 1) setUploading(false);

return;
}

controller.enqueue(chunk.value);
bytesRead += chunk.value.length;
setFileProgress(Math.floor((bytesRead / totalSize) * 100));
},
})
: files[i],
// @ts-expect-error
duplex: supportsRequestStreams ? "half" : undefined,
headers: {
"content-type":
(files[i].name.split(".").at(-1) as string).toLowerCase() ===
"mov"
? "video/mp4"
: files[i].type ||
fileTypes[files[i].name.split(".").at(-1) as string],
},
method: "PUT",
});

if (!uploadReq.ok) {
shouldRecall = true;
break;
}
} catch (e) {
console.error(e);
const increaseProgress = (e: ProgressEvent) => {
bytesRead += e.loaded;
setFileProgress(Math.floor((bytesRead / totalSize) * 100));
};

for (let i = 0; i < upload_urls.length; i++) {
const xhr = new XMLHttpRequest();

xhr.open("PUT", upload_urls[i], false);
xhr.setRequestHeader(
"content-type",
(files[i].name.split(".").at(-1) as string).toLowerCase() === "mov"
? "video/mp4"
: files[i].type ||
fileTypes[files[i].name.split(".").at(-1) as string],
);

xhr.upload.addEventListener("progress", increaseProgress);
xhr.upload.onabort = () => {
shouldRecall = true;
break;
}
};
xhr.upload.onerror = () => {
shouldRecall = true;
};

xhr.send(files[i]);
}

if (shouldRecall) {
Expand Down

0 comments on commit 2411714

Please sign in to comment.