From f3104e84ecd1cd9c76cf62fdd405a2b71f2f4352 Mon Sep 17 00:00:00 2001 From: Blaster4385 Date: Fri, 26 Jul 2024 14:52:03 +0530 Subject: [PATCH] refactor: improved progress tracking --- client/assets/index.js | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/client/assets/index.js b/client/assets/index.js index b18b3d8..0e9d61a 100644 --- a/client/assets/index.js +++ b/client/assets/index.js @@ -120,18 +120,9 @@ async function uploadFileInChunks(file, progressFill) { formData.append('chunkCount', chunkCount); formData.append('fileName', file.name); - const response = await fetch(`${baseUrl}/upload_chunk`, { - method: 'POST', - body: formData, - }); - - if (!response.ok) { - throw new Error(`Error uploading chunk ${chunkIndex}: ${response.statusText}`); - } + await uploadChunk(formData, progressFill, uploadedSize, fileSize); uploadedSize += chunk.size; - const progress = Math.round((uploadedSize / fileSize) * 100); - progressFill.style.width = `${progress}%`; } // Call upload_complete endpoint @@ -154,6 +145,33 @@ async function uploadFileInChunks(file, progressFill) { window.location.href = pageUrl; } +async function uploadChunk(formData, progressFill, uploadedSize, fileSize) { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open('POST', `${baseUrl}/upload_chunk`, true); + + xhr.upload.onprogress = (event) => { + if (event.lengthComputable) { + const totalUploaded = uploadedSize + event.loaded; + const progress = Math.round((totalUploaded / fileSize) * 100); + progressFill.style.width = `${progress}%`; + } + }; + + xhr.onload = () => { + if (xhr.status === 200) { + resolve(); + } else { + reject(new Error(`Error uploading chunk: ${xhr.statusText}`)); + } + }; + + xhr.onerror = () => reject(new Error('Network error occurred')); + + xhr.send(formData); + }); +} + function generateUploadId() { return Math.random().toString(36).substr(2, 9); }