Implementing File Uploads in Spring Boot Applications

File uploading is an essential feature in many applications, allowing users to upload documents, images, and other data to the server. Spring Boot makes it easy to handle file uploads through its built-in support for MultipartFile. In this post, we will walk through the steps to implement file uploads in a Spring Boot application.

Setting Up Your Spring Boot Application

To begin, create a simple Spring Boot application using Spring Initializr. Ensure to include:

  • Spring Web

1. Adding Dependencies

If you are using Maven, add the necessary dependencies to your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. Configuring File Upload Properties

Configure file upload capabilities in application.properties. Here you can set the maximum size for uploaded files:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

Creating a File Upload Controller

Now, let’s create a controller that will handle file uploads:

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@RequestMapping("/api/files")
public class FileUploadController {

    private final String UPLOAD_DIR = "uploads/";

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam MultipartFile file) {
        try {
            // Create directory if not exists
            Files.createDirectories(Paths.get(UPLOAD_DIR));

            // Save file to the target location (assuming it is not empty)
            Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
            Files.write(path, file.getBytes());

            return ResponseEntity.ok("File uploaded successfully: " + file.getOriginalFilename());
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to upload file: " + e.getMessage());
        }
    }

    @GetMapping("/upload")
    public ModelAndView showUploadForm() {
        return new ModelAndView("fileUploadForm"); // Create a view to upload files
    }
}

Creating the File Upload Form

Create an HTML template for the file upload form in src/main/resources/templates called fileUploadForm.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <h2>Upload a File</h2>
    <form action="/api/files/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" required><br>
        <button type="submit">Upload</button>
    </form>
</body>
</html>

Running and Testing Your Application

Run your Spring Boot application. Access the file upload form at http://localhost:8080/api/files/upload. Select a file and submit the form to upload it to the server.

You can also test the upload functionality using Postman:

curl -X POST -F "file=@/path/to/your/file.txt" http://localhost:8080/api/files/upload

Conclusion

Implementing file uploads in a Spring Boot application is straightforward with the help of Spring’s multipart file support. This capability allows you to enhance user interactions by enabling users to upload documents, images, and more.

For additional advanced topics and best practices related to file handling and Spring Boot, explore the extensive learning resources available at ITER Academy to further enhance your development skills.

To learn more about ITER Academy, visit our website.

Scroll to Top