I am trying to play with codes. However, why does Webpage NEVER allow the to access any local files.
Means if you write
<img src="c:\ImageFolder\Angelica.jpg"/>
in the jsp file, it will NOT work.
WHY NOT? Is there a way for me to retrieve an image from my C Drive and display in webpage?
src attribute of img tag is used to refer relative path or url of source i.e source can be inside your web container or hosted by some other website. You cannot use absolute path for source, as you cannot refer to files outside container.
As a work around, you can create a servlet that can load file from outside of your web container and then write/stream file to your response. You will provide path of file to the servlet and that servlet will serve the file to you.
Suppose if you create a servlet for serving file with name 'FileServlet', and this FileServlet takes 'path' as parameter to fetch file, you img tag will look something like this:
<img scr="FileServet?path=c:\\parentDirectory\file.jpg">
refer: File Servlet by BalusC for detailed working.
> :)Try
<html>
<%#page import="java.io.File"%>
<%#page import="java.io.IOException"%>
<%#page import="java.awt.image.BufferedImage"%>
<%#page import="javax.imageio.ImageIO"%>
<%#page import="java.io.ByteArrayOutputStream"%>
<%#page import="java.math.BigInteger"%>
<%#page import="javax.xml.bind.DatatypeConverter"%>
<%#page import="java.awt.image.BufferedImage"%>
<head>
</head>
<body>
<%
//write image
try{
String imgName="C:\\PATROL_SITE_IMAGES\\17-Jun-2016\\7588519616\\249_R.jpg";
BufferedImage bImage = ImageIO.read(new File(imgName));//give the path of an image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bImage, "jpg", baos );
baos.flush();
byte[] imageInByteArray = baos.toByteArray();
baos.close();
String b64 = DatatypeConverter.printBase64Binary(imageInByteArray);
%>
<img class="img-responsive" src="data:image/jpg;base64, <%=b64%>"/>
<%
}catch(IOException e){
System.out.println("Error: "+e);
}
%>
</body>
</body>
</html>
Related
I have a controller that create model attribute and passes to the view "partial.html" to generate output
partial.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home page</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<p>
<span th:text="'Today is: ' + ${message}"></span>
</p>
</body>
</html>
and inside a controller method
model.addAttribute("message", search);
How to do I get Htlm Output to a string inside controller method?
like this
String htmlOutput="from partial.html";
Let's say you have a HTML file with two variable name and todayDate.
You want to process it and want to store it in a string / database / AWS S3.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<p>Hello</p>
<p th:text="${name}"></p>
<p th:text="${todayDate}"></p>
</body>
</html>
Your HTML file location is src/main/resources/templates/home.html
By using the below function you can get the final processed HTML as:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p>Hello</p>
<p>Manoj</p>
<p>30 November 2019</p>
</body>
</html>
import org.thymeleaf.context.Context;
#GetMapping("/")
public void process() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("templates/");
templateResolver.setCacheable(false);
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
// https://github.com/thymeleaf/thymeleaf/issues/606
templateResolver.setForceTemplateMode(true);
templateEngine.setTemplateResolver(templateResolver);
Context ctx = new Context();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
Calendar cal = Calendar.getInstance();
ctx.setVariable("todayDate", dateFormat.format(cal.getTime()));
ctx.setVariable("name", "Manoj");
final String result = templateEngine.process("home", ctx);
System.out.println("result:" + result);
}
If you're using the usual Spring MVC approach, as Joanna says you're doing things in the wrong order. The Controller creates the model and specifies the view, and then after that the view is rendered by the Thymeleaf template that uses the model.
If, on the other hand, you're trying to render Thymeleaf templates yourself (rather than sending them to the user's browser directly, maybe for use in HTML email or to store prerendered pages in a database or something), then you'd need to create your own Thymeleaf Template Engine to use. Refer to the "Creating and configuring the Template Engine" section of the documentation for details. You can create your own Engine, and then use its process method to get the result of the template to put into a variable for further use.
You may looking for this, getting directly the result HTML, just ignore the email part of the post.
Then, you can create this:
final Context ctx = new Context(locale);
ctx.setVariable("name", recipientName);
ctx.setVariable("subscriptionDate", new Date());
ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
ctx.setVariable("imageResourceName", imageResourceName);
// so that we can reference it from HTML
final String htmlContent = this.templateEngine.process("html/email-inlineimage.html", ctx);
So you have the htmlContext of rendered thymeleaf template (with vars)
Once the control goes out to view processor (JSP/Thymeleaf etc), it will not be coming back to controller. You will be able to get the raw html response in a customFilter, but not in the Controller.
How can I add, using localhost or Server, an image to be included in an e-mail that is sent via Spring with Thymeleaf?
This is my controllerMail.java:
final Map<String, String> inlineResources = new HashMap<String, String>();
Set<String> folderPath = new TreeSet<>();
for (File file : files) {
certificateFile = file.getCertificateFile();
String img = certificateFile.toString();
inlineResources.put("file", img);
}
inlineResources.put("img1", "/template/email/img/myImg.png");
And this my html mail:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:remove="all">Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body style="font-family:Trebuchet MS;">
<p>TEXT EMAIL</p>
<img style="max-width: 100%;" th:src="'cid:img1'" />
<img style="max-width: 100%;" th:src="'cid:file'" />
</body>
</html>
certificateFile return this path: /srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg
So my mail.html is located on my project in src/main/resources in /template/email. In this case img1 is correct find on email (it is located in the same path /template/email/img) but file return this log error:
Invalid resource: /srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg
Failed messages: javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.FileNotFoundException: class path resource [/srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg] cannot be opened because it does not exist
How i can fix this problem?
While the attachment of this file to email it works properly.
The solution for this problem is to use "file:" before the "pathImg":
String pathImg = certificateFile.toString().replace('\\', '/'); inlineResources.put("img", "file:"+pathImg);
I use tomcat 5.5, JSF 1.2, Spring 3
I have the servlet that passes file from disk to browser. The problem occures when that file has a text/html mime type.
I can't know what encoding that file might have so I can't set correct response encoding.
That's the code of servlet
private void handleFILERequest(final FacesContext context) throws UnsupportedEncodingException {
String filePath = AbstractBean.getStrRequestScopeAttribute(FILE_PATH);
String mimeType = AbstractBean.getStrRequestScopeAttribute(FILE_MIME_TYPE);
String fileName = AbstractBean.getStrRequestScopeAttribute(FILE_NAME);
byte[] data = getFile(filePath);
HttpServletResponse response = AbstractBean.getResponse();
response.reset();
response.setContentType(mimeType);
response.setContentLength(data.length);
if (fileName == null || "".equals(fileName)) {
response.addHeader("Content-Disposition", "attachment; filename=\"downloadFile\"");
} else {
response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
}
try {
response.getOutputStream().write(data);
} catch (Exception exception) {
LOG.error(exception.getMessage());
}
context.responseComplete();
}
private byte[] getFile(final String path) {
return IOUtils.readFile(path);
}
That problem occurs only when mime type of a file is text/html. Somehow that byte stream is re-encoded after I pass it to response outputstream. Also the html tag is slightly changed as you can see below. I think that servlet container do that but I am not sure.
Is there a way to detect file encoding to set it as response encoding or at least to prevent further re-encoding of response stream?
At least I'd like to know who changes that byte stream, tomcat, spring, jsf or...?
Here come a part of file on disk and resulting downloaded file in browser:
File on disk (cyrillic symbols, but no encoding defined):
<html>
<head>
<link HREF="/vestnik/csstyles/article.css" REL="stylesheet">
<title>Л.О. Бутакова. Опыт классификации ошибок ...</title>
</head>
...
File that I get in browser:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link HREF="/vestnik/csstyles/article.css" REL="stylesheet">
<title>пїЅ.пїЅ. пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ. пїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅ ...</title>
</head>
...
Thanks in advance.
You can use UTF-8 encoding
String str = new String(data); //set your data in this object
response.setContentType("text/plain");
InputStream input = new ByteArrayInputStream(str.getBytes("UTF8"));
I'm working with a site using client-side templates through knockout.js.
The backend api, and login, is written in rails.
What I want to do is have each client-side html template in a separate file, and then have those templates lifted into the page using the templates. Similar to how javascript files are lifted in.
So I have a directory in my app/assets called templates
Each template in the directory should be added to the page in a script tag with the type="text/html"
I've gotten so far as to product the actual templates content now I just want to put it in the html.erb file in the head property.
However it always lands in the Body as normal text, not as HTML.
I've defined the following method in my controller:
def html_templates
output = ''
templates = Dir.glob 'app/assets/templates/*'
templates.each { |template|
file = File.open(template, "rb")
output += '<script type="text/html" id="'+(File.basename template, '.html')+'">'
output += file.read
output += '</script>'
}
return output
end
I try to add it to the .erb layout file like so:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<%= html_templates %>
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
Yet the output is always put in the body, with all my html escaped.
Also, if anyone has better solutions to have to solve this. Please, recommend.
Thanks :) so basically you should use raw method whenever you don't want output to be escaped
I would like to convert BufferedImage to an image that will display on JSP page. How can I achieve this?
First, JSP is a view technology providing a template to write HTML/CSS/JS in and the ability to interact with backend Java code to control page flow and access backend data. Your problem is more in HTML.
Now, to display an image in a HTML page, you need the HTML <img> element. To define/allocate an image, you just have to let the src attribute point to an URL. E.g.
<img src="url/to/image.jpg" />
(it can be either relative to the current context, or an absolute URL, e.g. starting with http://)
If the image is dynamic, as in your case, you need to have a Servlet which listens on the url-pattern matching the image URL. E.g.
<img src="imageservlet/image.jpg" />
(here the servlet is obviously to be mapped on an URL pattern of /imageservlet/* and the image identifier, here the filename, is here available by request.getPathInfo())
The <img src> will fire a GET request, so you just have to implement doGet() method of the servlet. To send a HTTP response all you need to do is to write some content to the OutputStream of the response, along with a set of response headers representing the content (Content-Type, Content-Length and/or Content-disposition). You can use ImageIO#write() to write a BufferedImage to an OutputStream.
You can find a basic example of such an image servlet here. You just have to replace Files#copy() with ImageIO#write().
response.setContentType("image/png");
ImageIO.write(bufferedImage, "png", response.getOutputStream());
As a completely different alternative, you can also let the servlet convert the image to a Base64 encoded string and pass it on to the JSP:
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", output);
String imageAsBase64 = Base64.getEncoder().encodeToString(output.toByteArray());
request.setAttribute("imageAsBase64", imageAsBase64);
request.getRequestDispatcher("/WEB-INF/some.jsp").forward(request, response);
And finally show it in the forwarded JSP using the data URI scheme as below:
<img src="data:image/png;base64,${imageAsBase64}" />
You only need to keep in mind that this doesn't give the server nor the client the opportunity to cache the image. So this approach is plain inefficient in case the image is not temporary.
See also:
How to retrieve and display images from a database in a JSP page?
Simplest way to serve static data from outside the application server in a Java web application
You need not convert BufferedImage to Image to display it on the jsp page. Because, Java 6 JAXB provides javax.xml.bind.DatatypeConverter.printBase64Binary(byte[]) String to convert byte[] in to base 64 string. The base 64 string can be displayed using the <img html tag by specifying the source data as base 64 i.e. src="data:image/jpg;. Here is the sample program referred from this post.
sample.jsp (test passed) :
<%#page import="java.awt.image.BufferedImage"%>
<%#page import="javax.imageio.ImageIO"%>
<%#page import="java.io.*"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
BufferedImage bImage = ImageIO.read(new File("/home/visruth/Desktop/Visruth.jpg"));//give the path of an image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bImage, "jpg", baos );
baos.flush();
byte[] imageInByteArray = baos.toByteArray();
baos.close();
String b64 = javax.xml.bind.DatatypeConverter.printBase64Binary(imageInByteArray);
%>
<div>
<p>As of v6, Java SE provides JAXB</p>
<img src="data:image/jpg;base64, <%=b64%>" alt="Visruth.jpg not found" />
</div>
</body>
</html>
IMO, this approach is perfect for small sized images like <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" alt="thumbnail" height="200">. Otherwise using direct url of the image will be fine in src attribute eg:- <img src="uri-of-image/profile-pic.jpg" width="600" alt="No Profie Pic" height="600">