Hackforge Academy

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");
}

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community