Spring Boot File Upload Guide

In Spring Boot, implementing file upload functionality typically requires using the MultipartFile object from Spring MVC to receive and handle the uploaded file. Below is a simple example code for implementing file upload functionality.

  1. Create a Controller class to handle file upload requests.
@RestController
public class FileUploadController {

    private final String UPLOAD_DIR = "uploads/";

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            Path filePath = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
            Files.write(filePath, file.getBytes());
            return "File uploaded successfully!";
        } catch (IOException e) {
            return "Failed to upload file!";
        }
    }
}
  1. Configure the maximum file upload size in the application.properties file.
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
  1. Create an HTML form for uploading files.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <button type="submit">Upload</button>
    </form>
</body>
</html>

By following the above steps, you can achieve a basic file uploading function. When a user selects a file in an HTML form and clicks the upload button, the file will be transferred to the specified directory and a message indicating success or failure will be returned. You can expand and optimize the file uploading function according to actual needs.

bannerAds