DEV Community

Surhid Amatya
Surhid Amatya

Posted on

Multipart Image Upload, Part 3: Building the Multipart Upload API

Multipart Image Upload: A Practical Guide for Web, Mobile and Backend
Part 1: Understanding Chunked Multipart Upload
Part 2: Chunking the Image Locally
Part 3: Building the Multipart Upload API (this post)
Part 4: Making Uploads Reliable and Resumable
Part 5: Production Architecture and Cross-Platform Implementation

The client now has a pile of byte ranges. This part builds the server that receives them, figures out which is which, stores them, and rebuilds the image at the end. It's Spring Boot, but nothing here is specific to it.

What a part request looks like

Each chunk is a multipart/form-data request with two text fields and one binary field:

POST /api/uploads/abc-123/parts
Content-Type: multipart/form-data; boundary=----xyz

partNumber = 3
totalParts = 6
chunk      = <binary data>
Enter fullscreen mode Exit fullscreen mode

This is the idea the whole series rests on: the binary data doesn't say "I am part 3." The bytes are just bytes. What identifies the chunk is the metadata around it, the uploadId in the URL and the partNumber field. Lose those and the chunk can't be placed.

The controller

@RestController
@RequestMapping("/api/uploads")
@RequiredArgsConstructor
public class UploadController {

    private final UploadService uploadService;

    @PostMapping(
        value = "/{uploadId}/parts",
        consumes = MediaType.MULTIPART_FORM_DATA_VALUE
    )
    @PreAuthorize("hasScope('UPLOAD_WRITE')")
    public ResponseEntity<PartReceipt> uploadPart(
        @PathVariable String uploadId,
        @RequestParam int partNumber,
        @RequestParam int totalParts,
        @RequestPart("chunk") MultipartFile chunk
    ) throws IOException {
        PartReceipt receipt = uploadService.savePart(
            uploadId,
            partNumber,
            totalParts,
            chunk
        );
        return ResponseEntity.ok(receipt);
    }
}
Enter fullscreen mode Exit fullscreen mode

@RequestPart("chunk") binds the binary field and @RequestParam binds the text ones. The controller stays thin and hands everything to a service, so validation and storage don't leak into the HTTP layer.

Spring caps multipart sizes by default. Set the limits just above your chunk size instead of raising them globally:

spring.servlet.multipart.max-file-size=8MB
spring.servlet.multipart.max-request-size=8MB
Enter fullscreen mode Exit fullscreen mode

Validate before storing

Don't trust the numbers the client sends. Check them against the session the server created:

public PartReceipt savePart(
    String uploadId,
    int partNumber,
    int totalParts,
    MultipartFile chunk
) throws IOException {
    UploadSession session = sessionStore.find(uploadId);

    if (isNull(session)) {
        throw new UploadNotFoundException(uploadId);
    }
    if (partNumber < 1 || partNumber > session.getTotalParts()) {
        throw new InvalidPartException(partNumber);
    }
    if (totalParts != session.getTotalParts()) {
        throw new InvalidPartException("totalParts mismatch");
    }
    if (chunk.isEmpty() || chunk.getSize() > session.getChunkSize()) {
        throw new InvalidPartException("bad chunk size");
    }

    Path target = partPath(uploadId, partNumber);
    chunk.transferTo(target);

    return new PartReceipt(uploadId, partNumber, chunk.getSize());
}
Enter fullscreen mode Exit fullscreen mode

The real totalParts was recorded when the upload was created. The value in the request is only a consistency check, and a mismatch means the client is confused.

Where parts go

Each part is its own file, in a directory named after the upload:

uploads/
  abc-123/
    part-000001
    part-000002
    part-000003
    part-000004
Enter fullscreen mode Exit fullscreen mode

Zero-padded names matter. Sorted as strings, part-10 lands before part-2, which is a classic reassembly bug. Better to skip sorting and build the path from the part number when you need it:

private Path partPath(String uploadId, int partNumber) {
    return root.resolve(uploadId)
        .resolve(String.format("part-%06d", partNumber));
}
Enter fullscreen mode Exit fullscreen mode

Also check uploadId against a strict pattern, a UUID for example, before it goes anywhere near a path. An uploadId of ../../etc is a path traversal.

Out-of-order requests

With parallel uploads or retries, parts rarely show up in order. Say they arrive as 3, 1, 4, 2:

Received:  3, 1, 4, 2
Stored:    part-000001, part-000002, part-000003, part-000004
Enter fullscreen mode Exit fullscreen mode

Each lands in the right file because the filename comes from partNumber, not from when it arrived. Arrival order never matters, and that's the reason the protocol labels every part explicitly.

The complete endpoint

When the client thinks it's done, it calls:

POST /api/uploads/abc-123/complete
Enter fullscreen mode Exit fullscreen mode

The server checks that every part exists, then combines them in order:

Check parts
   1 ✓
   2 ✓
   3 ✓
   4 ✓
      ↓
   Combine
      ↓
 Final image
Enter fullscreen mode Exit fullscreen mode
public FinalFile complete(String uploadId) throws IOException {
    UploadSession session = sessionStore.require(uploadId);

    List<Integer> missing = IntStream
        .rangeClosed(1, session.getTotalParts())
        .filter(n -> !Files.exists(partPath(uploadId, n)))
        .boxed()
        .toList();

    if (!missing.isEmpty()) {
        throw new IncompleteUploadException(uploadId, missing);
    }

    Path output = finalPath(uploadId, session.getFileName());

    try (OutputStream out = Files.newOutputStream(output)) {
        for (int n = 1; n <= session.getTotalParts(); n++) {
            Files.copy(partPath(uploadId, n), out);
        }
    }

    cleanupParts(uploadId);
    return new FinalFile(output, Files.size(output));
}
Enter fullscreen mode Exit fullscreen mode

Two things to notice. It checks every part before writing anything, and reports which are missing, so the client knows exactly what to resend. And it streams one part at a time into the output file, so a several-hundred-megabyte image never sits in memory.

After assembling, compare the output size with the fileSize declared at creation. Parts 4 and 5 add checksums on top of that.

What to return

Keep responses small. For a part, return the part number and the size received. For failures, use a real status: 404 for an unknown upload, 400 for a malformed part, 409 for a conflict. When complete is called too early, return the list of missing parts so the client doesn't have to guess.

Where this stops

The server is mostly bookkeeping: trust the metadata over arrival order, validate against the session, name storage after the part number, join in sequence at the end.

It doesn't handle dropped connections, duplicate sends or an app that dies halfway. That's part 4.

Top comments (0)