Search code examples
javaspring-bootfile-uploadbackend

Image upload is not working in Spring Boot


I am building a web app using Spring Boot and I need the user to upload image. I am stuck at the backend of this problem. I have written the following code in controller. The app is running fine and when I upload the file through postman, it returns the image URL with status 200(ok) but the file does not get added to the folder. Please suggest what is wrong here. Please keep it as detailed as possible.

Here's my code to upload image that I have written in the controller

@PostMapping("/image/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        String message = "Image is successfully uploaded";
        try {
            String uploadPath = staticDir+"testfile_"+System.currentTimeMillis()+"_"+file.getOriginalFilename();
            file.transferTo(new File(uploadPath));
            message = "Image URL : " + uploadPath;
            return ResponseEntity.status(HttpStatus.OK).body(message);
        } catch (Exception e) {
            LOGGER.error("Exception occurred: {}",e);
            message = "Could not upload the file: " + file.getOriginalFilename() + "!";
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
        }

    }

I have annotated staticDir with @Value to get it's value from application.properties

@Value("${static.dir.path}")
    private String staticDir;

application.properties static.dir.path=C:\Users\rjuna\IdeaProjects\visitor-management-system\images

Then I have a configuration for application to access the image through port 8080.

@Configuration
@EnableWebMvc
public class MvcConfig  implements WebMvcConfigurer {
@Value("${static.dir.path}")
private String staticDir;

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
          .addResourceHandler("/vms/**")
          .addResourceLocations("C:/Users/rjuna/IdeaProjects/visitor-management-system/images/");
}
}

"/vms/**" is a pattern. App will find any file of URL with this pattern in the location given just below the pattern. Now I am searching with this URL

localhost:8080/vms/testfile_1681807188450_My_Photo.jpg

But I am getting 404- Not found, both in the browser and postman. The API returns the image URL which is the file location in my computer. Though I want to access the image through the application i.e. through localhost:8080 and that is not working. Please suggest a solution for this.


Solution

  • The file is being written to the incorrect location because of a missing path separator / or \.

    Either

            String uploadPath = staticDir+"/testfile_"+System.currentTimeMillis()+"_"+file.getOriginalFilename();
    

    Or

    static.dir.path=C:\Users\rjuna\IdeaProjects\visitor-management-system\images\