Spring MVC как добавить изображение и вывести из mysql

Пытаюсь разобраться как добавлять изображения из формы и потом выводить их на основной странице.

У меня есть модель для файла

@Entity
@Table(name = "item")
public class Items {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long item_name;
    private String title;
    private String price;
    private String min_desc;
    @Lob
    private byte[] image;

    public Items() { }

    public Items(String title, String price, String min_desc, byte[] image) {
        this.title = title;
        this.price = price;
        this.min_desc = min_desc;
        this.image = image;
    }

И есть добавление

public String add(@RequestParam String title, @RequestParam String price, @RequestParam("file") MultipartFile file,@RequestParam String desc, Model model) throws IOException {
            itemRepo.save(new Items(title,price,desc,file.getBytes()));
            return "index";
        }

Но таким способом корректно не работает, не понимаю как сделать правильно вывод и ввод изображения!!!


Ответы (1 шт):

Автор решения: Алексей Осецкий
  1. Преобразование Blob в массив байт
blob.getBytes(1, (int) blob.length());
  1. Controller
@GetMapping("/img/{id}")
public void getImage(@PathVariable("id") Long id, HttpServletResponse response) {
        imageService.writeImageToRespose(id, response);
}
  1. Service
public void writeImageToRespose(Long id, HttpServletResponse response) {
        //store image in browser cache
        response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
        response.setHeader("Cache-Control", "max-age=2628000");

        //obtaining bytes from DB
        byte[] imageData = someEntityDao.getPhotoById(id);

        //Some conversion
        //Maybe to base64 string or something else
        //Pay attention to encoding (UTF-8, etc)
       
        //write result to http response
        try (OutputStream out = response.getOutputStream()) {
            out.write(convertedStringBytes);
        }
}
  1. Отобаржение в jsp
th:src="*{'/img/' + entity.id}"

Код не проверял

→ Ссылка