Spring Boot images uploading and serving

Viewed 35884

I'm making new Spring Boot app and want to be able to store and serve images, I want images to be stored in applications directory:
enter image description here

this is what uploading looks like for now:

@PostMapping("/")
@ResponseBody
public String upload(@RequestPart String title, @RequestPart MultipartFile img) throws IOException{
    String imgName = img.getOriginalFilename();
    Post p = new Post();
    p.setTitle(title);
    p.setImageName(imgName);
    postService.add(p);
    File upl = new File("images/" + imgName);
    upl.createNewFile();
    FileOutputStream fout = new FileOutputStream(upl);
    fout.write(img.getBytes());
    fout.close();
    return "ok";
}

this is how I want to get images

<img th:src="@{'images/' + ${post.imageName}}"/>

for now I get 404 and when I want to view some images in directory I get

Fatal error reading PNG image file: Not a PNG file

how should I do it to make it work?

3 Answers

You can store external files in a folder named /static in the same directory as your jar and spring will scan them by default. So if you have static/images/ you can reference your images with:

<img th:src="@{/images/img.ext}"/>

So you would want to use new File("/static/images/" + imgName);

Related