Inserting an Image from Local Directory in Thymeleaf Spring Framework (With Maven)

Inserting an image from local directory in thymeleaf spring framework (with maven)

I want you to look into the Thymeleaf's documentation of Standard URL Syntax and specifically the context-relative and server-relative url patterns.

Context-relative URL:

If you want to link resources inside your webapp then you should use
context relative urls. These are URLs which are supposed to be
relative to the web application root once it is installed on the
server. For example, if we deploy a myapp.war file into a Tomcat
server, our application will probably be accessible as
http://localhost:8080/myapp, and myapp will be the context name.

As JB Nizet the following will work for you as I have used thymeleaf personally in a webapp project,

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

and the test.png should be under your project root inside the webapp folder. Something navigated through roughly like,

Myapp->webapp->images->test.png

Eg:

<img th:src="@{/resources/images/Picture.png}" />

Output as:

<img src="/resources/image/Picture.png" />

When you hit http://localhost:8080/myapp/resources/images/Picture.png in you browser then you should be able to access the image for the above syntax to work. And your resources folder will probably under webapp folder of your application.

Server-relative URL:

Server-relative URLs are very similar to context-relative URLs, except
they do not assume you want your URL to be linking to a resource
inside your application’s context, and therefore allow you to link to
a different context in the same server

Syntax:

<img th:src="@{~/billing-app/images/Invoice.png}">

Output as:

<a href="/billing-app/showDetails.htm">

The above image will be loaded from an application different from your context and if an application named billing-app is present in your server.

Sourced from: Thymeleaf documentation

How to load an image in spring boot with thymeleaf?

After some digging found out that the issue was that Spring security was not enabled for the images folder. So added web.ignoring().antMatchers("/images/**"); in the configure method of the class that extends WebSecurityConfigurerAdapter and it worked.

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**");
web.ignoring().antMatchers("/scripts/**");
web.ignoring().antMatchers("/images/**");
}

Spring Boot displays images in some pages but not others

According to your configuration, the images are available from the root /.

So you should be able to use <img th:src="@{/images/logo.png}" /> in any page.

Can't load image with spring boot thymeleaf

Try changing to

<img src="../static/images/pirate.jpg" width="1000" th:src="@{images/pirate.jpg}"/>


Related Topics



Leave a reply



Submit