Home > Mobile >  Duplicate - How can I display an image using Springboot-Thymeleaf
Duplicate - How can I display an image using Springboot-Thymeleaf

Time:01-02

I've been trying to display an image using thymeleaf for awhile and having issues with it saving it as a byte array was no problem, however displaying it is extremely (for me at least) I followed a post with the question that was asked about it and had no results sadly, was hoping someone could help me with this problem

Controller trying to display the image

@GetMapping("/home")
public String index(Model model){
    model.addAttribute("clothingItems", itemService.findAll());
    return "index";
}

@GetMapping("/display/image/{id}")
public void displayItemImage(@PathVariable int id, HttpServletResponse response) throws IOException{

    response.setContentType("image/*");

    Item item = itemService.findItemById(id);

    InputStream is = new ByteArrayInputStream(item.getImage());
    IOUtils.copy(is, response.getOutputStream());
}

My Entity class

public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "post")
    private String text;

    @Lob
    @Column(name = "img")
    private byte[] image;

    @OneToOne(cascade = {CascadeType.DETACH,
                        CascadeType.MERGE,
                        CascadeType.PERSIST,
                        CascadeType.REFRESH})
    @JoinColumn(name = "category_id")
    private Category category;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

Trying to display it with thymeleaf

<div >
    <h2>Headwear</h2>
    <div  th:each="clothing : ${clothingItems}">
        <img th:src="@{'display/image/'   @{clothing.image}}">
    </div>

</div>

Result

I tried following this post Test Results

Here's the live result from your Live image

  • Related