Filip Resceanu
Filip Resceanu

Reputation: 21

How to display an image on html from database

I 'm a beginer with spring framework. I insert an image to postgresql database and i want to display it. the model class is:

@Data
@Entity
@Table(name="Item")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    private byte[] imageTo_display;
    private Long price;
    @ManyToOne
    private Cart cart;


}

I think the problem is at image tag but i don't know how to solve it . and the html is:

<th:block th:each="item:${listItems}">
                   <tr>
                       <td>[[${item.id}]]</td>
                       <td>[[${item.name}]]</td>
                       <td>[[${item.price}]]</td>
                       <td>    <img class="s-ava-alone-img" width="150" height="150" th:src="@{${item.imageTo_display}}"></td>
                   </tr>
                   <td>
                       <a class="h4 mr-3" th:href="@{'/users/edit/'+${item.id}}">Edit</a>
                       <a class="h4 mr-3" th:href="@{'/users/delete/' +${item.id}}">Delete</a>
                   </td>
               </th:block>

Upvotes: 0

Views: 163

Answers (1)

Metroids
Metroids

Reputation: 20477

The way you should do this is:

  1. Create a controller that just returns the byte[] array of the image:

     @GetMapping(value = "/image/{id}")
     public void view(HttpServletResponse response, @PathVariable(name="id") int id) throws Exception {
       response.setHeader("content-type", "image/jpg");
    
       Item item = ...; // Get the item based on id;
       OutputStream o = response.getOutputStream();
       o.write(item.imageTo_display);
       o.close();
     }
    
  2. Link to your image on the page:

     <th:block th:each="item: ${listItems}">
         <tr>
              <td th:text="${item.id}" />
              <td th:text="${item.name}" />
              <td th:text="${item.price}" />
              <td><img class="s-ava-alone-img" width="150" height="150" th:src="@{/image/{id}(id=${item.id})}"></td>
         </tr>
    
         <td>
             <a class="h4 mr-3" th:href="@{/users/edit/{id}(id=${item.id})}">Edit</a>
             <a class="h4 mr-3" th:href="@{/users/delete/{id}(id=${item.id})}">Delete</a>
         </td>
     </th:block>
    

Upvotes: 1

Related Questions