Home > other >  Cannot Load Image in Spring Boot
Cannot Load Image in Spring Boot

Time:09-21

I'm making a sport e-commerce website using Spring Boot and Thymeleaf and in the index of products page and edit page of a particular product, I can't view the image of the product. This is how the edit a product page (inspect on Chrome) looks

Here's the HTML Code for Edit a product. The line below the current image is the one generating the error for both edit and index.

<div class="form-group">
                <label for="">Image:</label>
                <input type="file" class="form-control" th:name="file" th:id="file">
                <img class="mt-2" src="#" alt="" id="imgPreview1">
                <br><br>
                <label for="">Current image:</label>
                <img style="width: 100px;" th:src="@{'media/' ${product.image}}"> 
            </div>

I get the image from my media folder in src/main/resources/static/media and I get the product name from the database. There's no error in fetching the name of the image file from the database. It looks like a path error but I can't seem to figure it out.

CodePudding user response:

In spring boot, pages are searched under "templates" folder and resources are mapped under "static" folder by default. To access an image file under static folder, try

/image-path/image.ext

For example, I have an src folder under static and it has some image, logo.png then,

/src/logo.png

CodePudding user response:

Your HTML or JSP page are always in ../resources/templates/ and your image path is ../resources/static/media/. To get image from static folder you need to go back using ../ from templates folder and go to media folder and get image...

Change:

../resources/static/media/liverpool_21_22_home_kit.jpg

To:

../media/liverpool_21_22_home_kit.jpg
  • Related