Back to results for “File Upload Handling”
Node.js › File Uploads & Media Processing

How would you implement resumable/chunked file uploads in Node.js to handle very large files over unreliable network connections?

Advanced

Answer

Chunked (resumable) uploads split a large file into smaller pieces on the client side, uploading each chunk as a separate request with metadata identifying its position within the overall file -- the server stores each received chunk (or appends it directly to a partially-assembled file) and, once all chunks have arrived, reassembles them into the complete file; if the connection drops mid-upload, only the remaining unsent chunks need to be retried, rather than restarting the entire upload from scratch.
app.post('/upload-chunk', upload.single('chunk'), async (req, res) => {
  const { uploadId, chunkIndex, totalChunks } = req.body;
  await fs.promises.rename(req.file.path, `./chunks/${uploadId}-${chunkIndex}`);

  const receivedChunks = await fs.promises.readdir('./chunks');
  if (receivedChunks.filter(f => f.startsWith(uploadId)).length === Number(totalChunks)) {
    await assembleChunksIntoFinalFile(uploadId, totalChunks);
  }
  res.json({ received: chunkIndex });
});
Real-world example A cloud-storage application supporting multi-gigabyte file uploads over potentially unstable mobile network connections implements chunked uploads, letting a user's upload resume from where it left off after a dropped connection rather than needing to restart the entire multi-gigabyte transfer.

Common follow-ups: How does a library like tus (an open protocol for resumable uploads) standardize this pattern rather than each application implementing it from scratch?;How do you handle cleaning up abandoned partial chunk uploads that are never completed?