Created
December 19, 2024 07:40
-
-
Save kidGodzilla/0e8c31ec40d5a755f86bf02198161ecb to your computer and use it in GitHub Desktop.
Chunked video uploads frontend/backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Frontend | |
const fileInput = document.querySelector('input[name="video"]'); | |
const file = fileInput.files[0]; | |
const chunkSize = 10 * 1024 * 1024; // 10MB | |
const totalChunks = Math.ceil(file.size / chunkSize); | |
for (let chunk = 0; chunk < totalChunks; chunk++) { | |
const start = chunk * chunkSize; | |
const end = Math.min(start + chunkSize, file.size); | |
const blob = file.slice(start, end); | |
const formData = new FormData(); | |
formData.append('video', blob); | |
formData.append('jobId', jobId); | |
formData.append('chunk', chunk); | |
// Post your upload with formData | |
... | |
} | |
// Backend | |
const uploadedChunks = await fs.readdir(chunkDir); | |
if (uploadedChunks.length === parseInt(totalChunks)) { | |
// Assemble the chunks | |
// Construct the assembled path | |
const assembledPath = path.join(__dirname, 'uploads', `${jobId}.${fileExtension}`); | |
const writeStream = fs.createWriteStream(assembledPath); | |
try { | |
for (let i = 0; i < totalChunks; i++) { | |
const chunkFile = path.join(chunkDir, `chunk_${i}`); | |
if (!fs.existsSync(chunkFile)) { | |
return res.status(400).send(`Missing chunk ${i}`); | |
} | |
const data = await fs.readFile(chunkFile); | |
writeStream.write(data); | |
} | |
writeStream.end(); | |
writeStream.on('finish', async () => { | |
// Handle your re-assembled upload | |
}); | |
} catch (err) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment