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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
