How would you implement resumable/chunked file uploads to support very large files over unreliable network connections?
Short answer
A chunked upload protocol splits a large file into smaller pieces uploaded via separate requests (each with a chunk index and total chunk count), with the server accumulating chunks (tracked via a temporary storage location keyed by an upload session ID) and assembling the…
Advertisement
AModel answer
A chunked upload protocol splits a large file into smaller pieces uploaded via separate requests (each with a chunk index and total chunk count), with the server accumulating chunks (tracked via a temporary storage location keyed by an upload session ID) and assembling the complete file only once all chunks have arrived -- allowing an interrupted upload to resume from the last successfully received chunk rather than restarting from scratch, essential for large files over unreliable connections.
[HttpPost("upload-chunk")]
public async Task<IActionResult> UploadChunk(string uploadId, int chunkIndex, int totalChunks, IFormFile chunk) {
var chunkPath = Path.Combine(_tempPath, uploadId, $"chunk-{chunkIndex}");
using var stream = File.Create(chunkPath);
await chunk.CopyToAsync(stream);
if (await AllChunksReceivedAsync(uploadId, totalChunks)) {
await AssembleChunksAsync(uploadId, totalChunks);
}
return Ok(new { chunkIndex, received = true });
}Real-world example
A cloud backup application uploading multi-gigabyte files over an unreliable mobile connection implements chunked, resumable uploads, letting a dropped connection resume from the last successfully uploaded chunk instead of restarting a multi-hour upload from zero.
Likely follow-ups
- How do you handle a client that never completes all chunks, leaving orphaned partial uploads?
- How does this compare to using a cloud storage provider's native resumable upload API (like Azure Blob's block upload)?
Related topics