Category: spring_boot
Spring Boot, file uploads
Published on 19 Jun 2026
Explanation
In Spring Boot, file uploads are
commonly handled using multipart/form-data.
The frontend
sends the file, and Spring Boot
receives it using MultipartFile.
Code:
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(
@RequestParam("file") MultipartFile file) {
return ResponseEntity.ok(
"File uploaded: " + file.getOriginalFilename(
));
}
Explanation
Frontend code to upload a file
to a Spring Boot REST API.
Code:
const formData = new FormData();
formData.append('file', selectedFile);
fetch('http://localhost:8080/upload', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => console.log(data));
Explanation
To save the uploaded file on
the server, use MultipartFile.transferTo().
Code:
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(
@RequestParam("file") MultipartFile file)
throws IOException {
Path path = Paths.get("uploads/" +
file.getOriginalFilename());
file.transferTo(path);
return ResponseEntity.ok(
"File uploaded successfully");
}
Explanation
If the requirement is to send
file content as JSON, convert the
file to Base64 and send it
in the request body.
Code:
{
"fileName": "students.csv",
"content": "SGVsbG8gV29ybGQ="
}
Explanation
Spring Boot API to receive a
file in JSON format and save
it to the server.
public class FileRequest {
private String fileName;
private String content;
}
Code:
@PostMapping("/upload-json")
public ResponseEntity<String> uploadJson(
@RequestBody FileRequest request)
throws IOException {
byte[] data = Base64.getDecoder().
decode(request.getContent());
Files.write(Paths.get("uploads/" +
request.getFileName()), data);
return ResponseEntity.ok(
"File uploaded successfully");
}