Thymeleaf email image not displayed - html

I'm using Thymeleaf with Spring Boot.
I'm trying to send a mail with a html template.
The mail is ok, the variable thymeleaf in the template are replace it's perfect, but, my only one problem is that the image are not displayed. It's just like if the image doen't exist.
The html template and the image ( Picture.png ) are on the same folder.
In the template I have try these multiples tries :
<img src="Picture.png" />
<img src="#{Picture.png}" />
<img th:src="|cid:${imageName}|" /> // by passing the "Picture.png" in the imageName variable
<img th:src="#{Picture.png}" />
But nothing is working, I need help thanks !

I answer my own question because I suceed to resolve the problem :
Just put like that <img src="cid:imageName"/> in the html file

Checkout the Thymeleaf's documentation especially the part for context-relative and server-relative url patterns.
If your project root directory is called myapp and you deploy it into a Tomcat server, your application will probably be accessible as http://localhost:8080/myapp, and myapp will be the context name.
So assuming the folder containing both the image and the html is located at:
myapp/resource/assets/(html and Picture.png exists)
the correct code to dynamically fetch the image is:
<img src="resource/assets/Picture.png" th:src="#{resource/assets/Picture.png}" />

Related

Embedding Image To HTML from Database

I have a scaffold which is used to update frontend information of the Home# Index. I'm unable to add the image int he given theme formate.
<section id="home" class="no-padding parallax mobile-height wow fadeIn" data-stellar-background-ratio="0.5" style="background-image:url(<%= image_tag detail.banner.url %>);">
Thanks.
It seems that details.banner.url evaluates to external url of placehold.it/1920x1200. If that's where the image is (which I doubt) you have to add http:// to the link, because right now it is looking for a placehold.it folder and not server address. If you're trying to read a file from your server, details.banner.url clearly returns the wrong path. If you want to put the image in the database then look into ActiveStorage or Paperclip.
Please go through this rails guide for asset pipeline
According to this guide, your code will be like this:
style="background-image:url(<%= asset_path detail.banner.url %>);"

Insert image into jsp page

I am sorry that I need to ask this but I already spent three days trying to do this. I am buidling Java Web application and I want to include image to JSP page. Project name is realestates and I have Files folder inside realestates folder.
My code is like this:
<img alt="govno" src="<%=request.getContextPath() + "/Files/kurac.jpg"%>" style="width: 400px; height: 300px;">
This is what gets generated on page after I open it in browser:
<img alt="govno" src="/realestates/Files/kurac.jpg" style="width: 400px; height: 300px;">
BUT, image is not dispayed, only alt "govno" is written. I have tried many many paths (relative, absolute, changed folder structure million times and whatever I could think of and find on internet but nothing helped). Who would say that such a thing will be so hard to do???
Folder structure on Tomcat server after deployment is:
webapps
- realestates
|- WEB-INF
|- Files
|- kurac.jpg
Here is a guy explaining it in less than a minute.
https://www.youtube.com/watch?v=dwjwSYOrnS8
So two things are required:
1.Add this line in some config xml file
<mvc:resources location="/files/" mapping="/files/**"></mvc:resources>
2.Include image into JSP page with this line
<img src='<c:url value="/files/korali.jpg"></c:url>' />
Looks like you got yourself (and everyone else) confused of where the image is.
From your question, it seems to be at webapps/realestates/Files/kurac.jpg, so this should work:
<img src="/realestates/Files/kurac.jpg">
From your first comment, it is at C:/Users/Lazar/Documents/workspace-sts-3.8.3.RELEASE/realestates/Files/kurac.jpg, so it will not be accessible via http://.
This won't work.
From your later comment, it is at /webapp/realestates/WEB-INF/Files/kurac.jpg.
Files inside WEB-INF are not publicly accessible.
This won't work either.
As a last resort, move the image file to webapps/ROOT directory.
Try http://localhost/kurac.jpg from your browser.
Replace localhost with your server hostname as necessary.
If it works, this will work as well:
<img src="/kurac.jpg">
If it doesn't, there is something wrong with your Tomcat configuration.
Try reinstalling.
I read your question and i have one solution for your problem you can use the INPUT STREAM for add an image in JSP page...
THIS IS JUST EXAMPLE...AND MAY HAVE ERROR BUT THIS IS THE WAY HOW TO INSERT IMAGE IN JSP...
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection =
DriverManager.getConnection(connectionURL, "user", "pass");
psmnt = connection.prepareStatement(
"insert into save_image(user, image) values(?,?)");
psmnt.setString(1, username);
ImageIO.write(image, "png", new File("C://image.png"));
File imageFile = new File("C://image.png");
FileInputStream fis = new FileInputStream(imageFile);
psmnt.setBinaryStream(2, (InputStream)fis, (fis.length()));
int s = psmnt.executeUpdate();
At first you must create image folder outside the WEB-INF directory and try that code <img src="${pageContext.request.contextPath}/Files/kurac.jpg"/>
Webpage never allows accessing any local files.
This means that if you write img src="c:\imagesfolder\abc.jpg" in the jsp file it will not work (it can work only in some editor but it will not work using a browser).
img src="http://localhost.8080/imageshow/sendimage/12/abc.jpg" width="100" height="100"

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

I have developed a project using this link: https://spring.io/guides/gs/serving-web-content/ I used maven to develop above project.
I have two html files under this. abc.html and xyz.html. To insert images in the html page, I have used the url like this:
<img src="https://example.com/pic_mountain.jpg" alt="Mountain View" style="width:304px;height:228px">
But I want to use an image file located in my server instead. I tried placing the file in the same directory of html file but its not working. I even tried giving full path but of no use. This is an ubuntu OS. Please help me out here. Is there any place where I can configure the base path or basically how to put an image from my local folder.
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
You need to understand how HTTP works. When the browser loads a page at URL
http://some.host/myWebApp/foo/bar.html
and the HTML page contains
<img src="images/test.png"/>
the browser will send a second HTTP request to the server to load the image. The URL of the image, since the path is relative, will be http://some.host/myWebApp/foo/images/test.png. Note that the absolute path is composed from the current "directory" of the page, concatenated with the relative path of the image. The path of the server-side JSP or thymeleaf template is completely irrelevant here. What matters is the URL of the page, as displayed in the address bar of the browser. This URL is, in a typical Spring MVC application, the URL of the controller where the initial request was sent.
If the path of the image is absolute:
<img src="/myWebApp/images/test.png"/>
then the browser will send a second request to the URL http://some.host/myWebApp/images/test.png. The browser starts from the root of the web server, and concatenates the absolute path.
To be able to reference an image, whetever the URL of the page is, an absolute path is thus preferrable and easier to use.
In the above example, /myWebAppis the context path of the application, that you typically don't want to hard-code in the path, because it might change. Thankfully, according to the thymeleaf documentation, thymeleaf understands that and provides a syntax for context-relative paths, which thus transforms paths like /images/test.png into /myWebApp/images/test.png. So your image should look like
<img th:src="#{/images/test.png}"/>
(I've never used thymeleaf, but that's what I deduce from the documentation).
And the test.png image should thus be in a folder images located under the root of the webapp.
Get link on Internet:
String src = "https://example.com/image.jpg";
HTML: <img th:src="#{${src}}"/>
I have used bellow like..
My image path is like bellow..
I have used bellow code for loading image
<img th:src="#{imges/photo_male_6.jpg}" >
It is working fine for me.
Recently I had similar issue, but in my case, the spring security was making a problem. As mentioned in other answers and documentation:
<img th:src="#{/img/values.png}" alt="Media Resource"/>
should be enough. But since the spring security has been added to my project, I had to all /img/ ** for get Requests and add addResourceHandlers. Here is the code:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(
"/webjars/**",
"/img/**",
"/css/**",
"/js/**")
.addResourceLocations(
"classpath:/META-INF/resources/webjars/",
"classpath:/static/img/",
"classpath:/static/css/",
"classpath:/static/js/");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
http.authorizeRequests().antMatchers(HttpMethod.GET, "/js/**", "/css/**", "/img/**" ,"/pressiplus", "/public/**", "/index", "/", "/login").permitAll();
http.authorizeRequests()
.antMatchers("/secure/admin/**").hasAnyRole("ADMIN","USER")
.antMatchers("/secure/admin/**").hasAnyRole("ADMIN")
.and()
.formLogin() //login configuration
.loginPage("/login")
.failureUrl("/login-error")
.loginProcessingUrl("/login")
.usernameParameter("email")
.passwordParameter("password")
.successHandler(myAuthenticationSuccessHandler())
.and()
.logout() //logout configuration
.logoutUrl("/logout")
.logoutSuccessHandler(myLogoutSuccessHandler)
.and()
.rememberMe()
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(7 * 24 * 60 * 60) // expires in 7 days
.and()
.exceptionHandling() //exception handling configuration
.accessDeniedHandler(accessDeniedHandler());
}
}
I hope this helps someone in the future
Who retrieve link dynamically use this pattern
<img class="image" th:src="#{'/resources/images/avatars/'+${theUser.avatar}}" alt="Avatar">
if you use like this (${theUser.avatar}) it will add ? in above version link look like this: /resources/images/avatars/photoname.png
As DimaSan said here https://stackoverflow.com/a/40914668/12312156
You should set image src like this:
<img src="../static/img/signature.png" th:src="#{img/signature.png}"/>

Image is not displaying when trying to display it from out of my project (local disk)

I'm trying to display image in my jsp from my local disk inside a web project. My Code is:
<img src="C:/Documents and Settings/chandhu/HelloWorld0.png" width="80px" height="100px" style="margin-left: 20px;"/>
After I run my application the image is not getting displayed. In src attribute it is additionally adding some source as mentioned below:
<img src="http://localhost:8080/Ecm/C:/Documents and Settings/chandhu/HelloWorld0.png" width="80px" height="100px" style="margin-left: 20px;"/>
Can anyone tell me what I am doing incorrectly?
You can't do this way.. It should be in reach of container. or you can write a servlet which will read disk file and make HTTPResponse
You mentioned using jsp , therefor i think you are working with web application ,in your WEB-INF folder create a directory named image or as you needed and put your image there .
Now you can access that from code as :
String fullPath = servletContext.getRealPath("/WEB-INF/image/" + image_file_name+ ".jpg");
InputStream is = new FileInputStream(fullPath );
Or you may use :
InputStream stream = this.getClass().getResourceAsStream("/WEB-INF/image/image_file_name.jpg");
to read stream directly .
related question may help you :
JPEG file in WEB-INF returned as null by ServletContext#getResource()
Cant retrieve an images from the WEB-INF folder ussing classLoader.getResourceAsStream()

Failed to load gived URL

i want to place images in my project web pages
i dont know how to point\path to the correct address of the image
i put the image in all of those folders but yet i dont see the image and
when i inspect it with fire bug i see that the browser failed to load the url.
<img src="../calendar_schedule.png"> <img src="calendar_schedule.png">
<img src="admin/calendar_schedule.png">
only when i use this path i can see the image - but it cant be the way
<img src="http://localhost:2734/Admin/Style/calendar_schedule.png">
If you use
<img src="Admin/Style/calendar_schedule.png">
it will append to your url like this:
http://localhost:2734/ExamplePage1/Admin/Style/calendar_schedule.png
You can use with first / to append directly to hostname
<img src="/Admin/Style/calendar_schedule.png">
And it looks like this:
http://localhost:2734/Admin/Style/calendar_schedule.png
As I understand, you want to avoid using of server host part. You can do the next:
<img src="/Admin/Style/calendar_schedule.png">