Return to site

📦☕ BINARY FILE UPLOADS in Java; inspired by Java Champion Rustam Mehmandarov

· java

Uploading a file to a REST API gets interesting when choosing between multipart data, framework helpers, and a raw binary body.

The right solution depends on the payload, portability, and file size.

🔸 TL;DR

▪️ Use Jakarta REST EntityPart for portable multipart uploads.

▪️ Use Quarkus @RestForm for cleaner Quarkus-specific code.

▪️ Use application/octet-stream when the body contains one file.

▪️ Stream large files instead of buffering them.

▪️ Never trust filenames, MIME types, or upload sizes.

🔸 1. PORTABLE MULTIPART WITH ENTITYPART

@POST

@Consumes(MediaType.MULTIPART_FORM_DATA)

public Response upload(List parts) throws IOException {

for (EntityPart part : parts)

if ("file".equals(part.getName()))

try (InputStream in = part.getContent()) {

in.transferTo(storageStream);

}

return Response.ok().build();

}

EntityPart is standard Jakarta REST 3.1. It handles text and binary parts while streaming through InputStream. The trade-off is some manual dispatching.

🔸 2. QUARKUS WITH @RESTFORM

@POST

@Consumes(MediaType.MULTIPART_FORM_DATA)

public Map upload(

@RestForm String description,

@RestForm FileUpload file) throws IOException {

Path target = Path.of("/storage", file.fileName());

Files.move(file.uploadedFile(), target);

return Map.of("storedAt", target.toString());

}

Quarkus stores the uploaded file temporarily on disk. file.uploadedFile() returns its Path; move it to permanent storage before the request ends.

🔸 3. RAW BINARY BODY

@POST

@Path("/raw")

@Consumes(MediaType.APPLICATION_OCTET_STREAM)

public Response uploadRaw(InputStream body) throws IOException {

body.transferTo(storageStream);

return Response.ok().build();

}

Use this when the body contains one file. It is portable and efficient, but metadata must go through headers or the URL.

🔸 TAKEAWAYS

▪️ Multipart fits files plus metadata.

▪️ Raw binary fits one machine-to-machine upload.

▪️ InputStream or temporary files protect the heap.

▪️ Set size limits to reduce denial-of-service risks.

▪️ Validate content instead of trusting headers.

▪️ Never write a client filename directly to disk.

▪️ With curl, use --data-binary to preserve bytes.

The real question is not “Which API looks nicest?” but “What payload contract and portability level does the system need?” 🚀

#Java #JakartaEE #JakartaREST #Quarkus #RESTAPI #FileUpload #BackendDevelopment #APIDesign #JavaDeveloper

Go further with Java certification:

Java👇

Spring👇

SpringBook👇

JavaBook👇