Mastering Multipart/Form-Data: From AJAX FormData to Spring Boot Backend

This guide explains how multipart/form-data enables sending JSON and binary data together, outlines its essential specifications, demonstrates front‑end FormData usage, and details Spring Boot back‑end handling with @RequestParam and @RequestPart annotations.

Tech Musings
Tech Musings
Tech Musings
Mastering Multipart/Form-Data: From AJAX FormData to Spring Boot Backend

Multipart/form-data Overview

Multipart/form-data enables a single HTTP request to carry multiple data types, such as JSON and binary files, which is why it is widely used in web forms.

Key Characteristics

The request Content-Type must be multipart/form-data and include a boundary string that separates each part.

Each part begins with the boundary, followed by Content-Disposition: form-data, the part’s name, and optionally a filename.

Each part may optionally specify its own Content-Type.

Front‑end Usage

In browsers the FormData API represents multipart data. The example below creates a request containing text fields, a user‑selected file, and a custom XML blob, then sends it with XMLHttpRequest:

var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number is converted to string
// HTML file input chosen by user
formData.append("userfile", fileInputElement.files[0]);
// JavaScript file‑like object (XML content)
var content = '<root>hey!</root>';
var blob = new Blob([content], {type: "text/xml"});
formData.append("webmasterfile", blob);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

Back‑end Handling with Spring Boot

Spring Boot can receive multipart requests using either @RequestParam or @RequestPart. The two annotations differ in how they convert incoming parts: @RequestParam relies on a Converter or PropertyEditor when the target type is not String or MultipartFile. @RequestPart uses HttpMessageConverters, which select a converter based on the part’s Content-Type. This is the same mechanism used by @RequestBody.

Guidelines:

For simple key=value form fields, prefer @RequestParam.

For JSON, XML, or other structured payloads, use @RequestPart and ensure the client sets the appropriate Content-Type for each part (as shown in the front‑end example).

Implementing custom converters or property editors adds extra code; because JSON is now the dominant data‑exchange format, @RequestPart is generally recommended for handling multipart requests in Spring Boot.

backendfrontendHTTPajaxFormDatamultipartspring-boot
Tech Musings
Written by

Tech Musings

Capturing thoughts and reflections while coding.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.