Skip to content

Instantly share code, notes, and snippets.

@GoodnessEzeokafor
Created January 2, 2025 15:49
Show Gist options
  • Save GoodnessEzeokafor/5212d2f0f3d88be00af63890c83300f0 to your computer and use it in GitHub Desktop.
Save GoodnessEzeokafor/5212d2f0f3d88be00af63890c83300f0 to your computer and use it in GitHub Desktop.
Multipart Upload
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Upload</title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data" onsubmit="return handleFormSubmit(event)">
<label for="video-upload">Upload Video:</label>
<input type="file" id="video-upload" name="video" accept="video/*,.mkv">
<button type="submit">Upload</button>
</form>
<script>
async function uploadLargeFile(file) {
const chunkSize = 5 * 1024 * 1024; // 5MB
const chunks = [];
let offset = 0;
while (offset < file.size) {
const chunk = file.slice(offset, offset + chunkSize);
chunks.push(chunk);
offset += chunkSize;
}
// Step 1: Initiate Upload
const initRes = await fetch('http://localhost:3421/api/v1/uploads/video/initiate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ fileName: file.name }),
});
const { uploadId } = await initRes.json();
// Step 2: Upload Chunks
const uploadedParts = await Promise.all(
chunks.map(async (chunk, index) => {
const formData = new FormData();
formData.append('partData', chunk);
formData.append('partNumber', index + 1);
formData.append('uploadId', uploadId);
formData.append('fileName', file.name);
const uploadRes = await fetch('http://localhost:3421/api/v1/uploads/video/part', {
method: 'POST',
body: formData,
});
const { ETag, PartNumber } = await uploadRes.json();
return { ETag, PartNumber };
})
);
// Step 3: Complete Upload
const completeRes = await fetch('http://localhost:3421/api/v1/uploads/video/complete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ uploadId, fileName: file.name, parts: uploadedParts }),
});
const { fileUrl } = await completeRes.json();
console.log('Uploaded file URL:', fileUrl);
return fileUrl;
}
async function handleFormSubmit(event) {
// Prevent the form from submitting immediately
event.preventDefault();
// You can handle the form data here, like performing validation
const fileInput = document.getElementById("video-upload");
const file = fileInput.files[0];
if (!file) {
alert("Please select a video file.");
return false;
}
const response = await uploadLargeFile(file);
return false; // prevent form submission if handled via JavaScript
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment