Sobes.tech
Middle

How to handle file (image) upload via HTTP request in Spring MVC and save it to disk?

sobes.tech AI

Answer from AI

To handle file uploads (for example, images) in Spring MVC, you can use the @RequestParam annotation with the MultipartFile type. Then, the file can be saved to disk using methods of this object.

Example controller:

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "No file selected";
        }
        try {
            // Path to save the file
            String uploadDir = "/path/to/save/";
            File dest = new File(uploadDir + file.getOriginalFilename());
            file.transferTo(dest); // save the file to disk
            return "File uploaded successfully: " + dest.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
            return "Error saving the file";
        }
    }
}

Important:

  • MultipartResolver must be enabled in Spring MVC configuration.
  • The save path must exist and have write permissions.
  • You can add checks for file type and size for security.