How to upload images to the static directory in Spring Boot projects?

In most cases, we need to develop the function to upload images in Java web projects. However, how to upload images to the static directory in projects driven by Spring boot?

Here is a demo to show how to upload images to the static directory in Spring Boot projects.

Upload images to the static directory in Spring Boot

In fact, it’s easy to implement the function if we know the process. In the front page, we can add the following code to display a simple upload image page.

<div class="bio-row">
  <form class="file-upload" enctype="multipart/form-data"  th:action="@{/image/upload}" th:method="POST">
      <input type="file" name="file"/><br>
      <input type="submit" value="Upload"/>
  </form>
</div>

Here, the method is POST instead of the GET.

@{/image/upload} is the RequestMapping in the Controller to handle the upload image request.

Then, the code to handle the upload image request in the Controller class as following:

    ...
    @Autowired
    private UploadService uploadService;

    @RequestMapping("/image/upload")
    public String uploadImage(HttpServletRequest request, Model model) throws FileNotFoundException {

        String imageDir = ResourceUtils.getURL("classpath:").getPath()+"static/img/";

        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");

        String imageUrl = uploadService.uploadImage(multipartFile, imageDir);

        return  "/admin/profile";
    }
    ...

The UploadService class as following:

@Service
public class UploadService {

    public String uploadImage(MultipartFile file, String imageDir) {
        Path rootLocation = Paths.get("/img/");

        String[] filepaths = file.getOriginalFilename().split("\\.");
        String generatedImageName = "";

        if (filepaths.length > 1)
            generatedImageName = UUID.randomUUID().toString() + "." + filepaths[filepaths.length - 1];

        try {
            file.transferTo(new File(imageDir, generatedImageName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return rootLocation.resolve(generatedImageName).toString();
    }
}

When everything is ok, we can simply images to the static directory, and it will be saved in the path: /… the path to the project…/target/classes/static/img/