With this code i am able to render a image from a servlet ,But my business says.I need to add a link say"www.google.com".If i click this image.Is there any way that i can access a image with the link on.I need to flush it directly from the servlet should not use jsp.Can any one please help me out.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServletContext sc = getServletContext();
String filename = sc.getRealPath("image.JPG");
resp.setContentType("image/jpeg");
// Set content size
File file = new File(filename);
resp.setContentLength((int)file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request , response);
// TODO Auto-generated method stub
}
}
You need to put an <a> element around the <img> element in the markup.
<a href="http://www.google.com">
<img src="imageServlet" />
</a>
By the way, the sc.getRealPath() suggests that your image file is already in public webcontent folder. Why not just using <img src="image.JPG"> instead? Or is the servlet heavily oversimplified?
In short you want to add a link say google.com and on click of it shows a image.
Firstly you don't need to send image as a response rather you need to anchor link and add javascript function onclick on that link.
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" +
"<HTML>\n" +
"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
"<a href='www.google.com'><img src='imagePath' /></a>\n" +
"</BODY></HTML>");
If I undestood correct you can return html with link on image:
<img src="yourImageRenderingServletPath">
So you will have one servlet that render html and second that render image. To prevent image buffering in browser you can add random param id = (new Random()).nextInt():
<img src="yourImageRenderingServletPath?id=124">
Related
I want to display image on the page that is returned by the java controller.
Java controller:
public FileSystemResource RetrieveLogo(#PathVariable("UniqueCode") String Code){
// get image file
return fileSystemResource;
}
at java script controller, I make a service call to get the image .
Javascript controller:
$scope.logo = function() {
rest.retrieveLogoForMerchant({id: 'abcd'}).$promise.then(function(data) {
console.log("-------------success--------- " + angular.toJson(data));
$scope.logoImage = angular.toJson(data);
});
}
Here the console prints -
{"0":"�","1":"�","2":"�","3":"�","4":"\u00.......etc}
On Html page
<img ng-src="{{logoImage}}" height="100" width="100"/>
On the page image displays blank and gives error in the console that -
http://localhost:9090/%7B%220%22:%22%EF%BF%BD%22,%221%22:%22%EF%BF%BD%22,%2…22%EF%BF%BD%22,%22246%22:%22\u0007%22,%22247%22:%22\u0014%22,%22248%22:%22 400 (Bad Request)
Suggest me ,that how can I display image properly.
Thanks
Try removing the the angular.toJSON method here:
$scope.logoImage = angular.toJson(data);
And also
I think you are loading image through binary data append proper image encoding
to the data Eg: ng-source={{data:image/png;base64........}}
You need to set the right content type in response inside your Java controller, see below function
public void displayImage(HttpServletResponse response, byte[] imageArray) throws ServletException, IOException {
System.out.println("Inside display Image function");
if (imageArray != null && imageArray.length > 0) {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
System.out.println("Image Array is not null :" + imageArray);
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
out.write(imageArray);
out.flush();
out.close();
} else {
System.out.println("Image is null");
}
}
Than you need to make sure append that appropriate header before data content while setting it to img tag.. #Naveen has already pointed about it in his answer. Basically you need to have something like this
<img src="data:image/png;base64,/*Your data part goes here*//>
You also need to encode the stream to Base64 before assigning it to img. I had below line in my jsp you can alter it to suit your need..
<img id="userProfileImg" height="150px" width="150px" name="userProfileImg" alt="../img/user_default_pic.png" src='data:image/jpg;base64,<%=Base64.encode(/*Blob data returned from database*/)%>'/>
Why don't you get the URL of the image via http (ajax call) and on success $scope.logoImage = data. data is the URL of the image retrieved via http.
I have a button (or link), and if I click on it, I want to open a HTML file. But I don't have the file, I have only the byte array of the HTML file. How could I open it in a new window, if I click on my opener button, to display the HTML file? Thank you!
You should make servlet which shows content of you html page. Example:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
// implement your page generations business logic in getHtmlPage
InputStream htmlPage = getHtmlPage();
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
I don't know how you exactly can determinate, which page you must show, so I encapsulate it into getHtmlPage method. Simplest way is make cache with pages and transfer into servlet page's key.
I have a servlet deployed under http://ip:8080/simple
The servlet is under package a.b.c
I have an html page in a.b.resources named Test.html.
The html has an img tag for an image.
In the servlet I do:
htmlFile = MyServlet.class.getResourceAsStream("/a/b/resources/Test.html");
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
byte[] bytes=new byte[htmlFile.available()];
htmlFile.read(bytes);
resp.setContentLength(bytes.length);
writer.print(new String(bytes));
writer.flush();
writer.close();
The html page appears on the browser but in the place of the image I see its alt description.
I have tried:
<img alt="Company A" src="./CompanyLogo.jpg">
<img alt="Company A" src="/a/b/resources/CompanyLogo.jpg">
<img alt="Company A" src="CompanyLogo.jpg">
But none of these works.
The jpg image is under /a/b/c/resources i.e. in the same directory as the HTML page.
I am using embedded Jetty.
What am I messing here?
The browser is trying to resolve those resources relative to the current request URI (as you see in browser address bar). Those resources of course does not exist in your public web content as you seem to have placed them in the classpath.
In order to solve this, you would really need to parse the HTML and change all domain-relative src and/or href attributes of <a>, <img>, <base>, <link>, <script>, <iframe>, etc elements to let them point to a servlet which streams those resources from the classpath to the HTTP response.
It's a bit of work, but Jsoup makes it easy. Here's an example which assumes that your servlet is mapped on an URL pattern of /proxy/*.
String proxyURL = request.getContextPath() + "/proxy/";
InputStream input = MyServlet.class.getResourceAsStream("/a/b/resources" + request.getPathInfo());
if (request.getRequestURI().endsWith(".html")) { // A HTML page is been requested.
Document document = Jsoup.parse(input, "UTF-8", null);
for (Element element : document.select("[href]")) {
element.attr("href", proxyURL + element.attr("href"));
}
for (Element element : document.select("[src]")) {
element.attr("src", proxyURL + element.attr("src"));
}
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(document.html());
}
else { // Other resources like images, etc which have been proxied to this servlet.
response.setContentType(getServletContext().getMimeType(request.getPathInfo()));
OutputStream output = response.getOutputStream();
byte[] buffer = new byte[8192];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
input.close();
Open it by http://yourdomain:yourport/contextname/proxy/test.html.
There is no way to do this without implementing a servlet that will read the image out of the resources file. Try this:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
byte[] bbuf = new byte[8192];
resp.setContentType(req.getSession().getServletContext().getMimeType( req.getPathInfo()));
InputStream in = MyImageServlet.class.getResourceAsStream("/"+req.getPathInfo());
OutputStream op = resp.getOutputStream();
int length;
while ((in != null) && ((length = in.read(bbuf)) != -1)){
op.write(bbuf,0,length);
op.flush();
}
in.close();
op.close();
}
then register it in your web.xml like so
<servlet-mapping>
<servlet-name>fetchimage</servlet-name>
<url-pattern>/fetchimage/*</url-pattern>
</servlet-mapping>
and then use it like so
<img alt="Company A" src="/fetchimage/a/b/resources/CompanyLogo.jpg">
You WILL need to implement a lot of error checking (A LOT OF ERROR CHECKING, just to clarify :)), filter the paths to make sure that someone can't just read your class files using the same technique, but some variation on this should work for you.
request.getRequestDispatcher("/a/b/Test.html").forward(request, response);
This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 3 years ago.
My ImageDAO looks like this:
public InputStream getPhotos(Long userid) throws
IllegalArgumentException, SQLException, ClassNotFoundException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultset = null;
Database database = new Database();
InputStream binaryStream = null;
try {
connection = database.openConnection();
preparedStatement = connection.prepareStatement(SQL_GET_PHOTO);
preparedStatement.setLong(1, userid);
preparedStatement.executeUpdate();
while(resultset.next()) {
binaryStream = resultset.getBinaryStream(4);
}
} catch (SQLException e) {
throw new SQLException(e);
} finally {
close(connection, preparedStatement, resultset);
}
return binaryStream;
}
My ImageServlet looks like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Getting user id from session
HttpSession session = request.getSession(false);
Long userid = (Long) session.getAttribute("user");
try {
InputStream photoStream = imageDAO.getPhotos(userid);
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams
input = new BufferedInputStream(photoStream, DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
output.close();
input.close();
}
//Redirect it to profile page
RequestDispatcher rd = request.getRequestDispatcher
("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
How should my JSP image src look like
<img src="What to put here">
Disclosure:
The servlet code is copied from this link http://balusc.blogspot.com/2007/04/imageservlet.html
Questions:
How to retreive image in JSP from ImageServlet. Someone in Stackoverflow said to put
<img src="URL to Servlet" />. But I don't what it means.
Is the above method correct way to retreive image from database? Or is there better way.
EDIT: My Web.xml looks like this
<servlet>
<servlet-name>Photo Module</servlet-name>
<servlet-class>app.controllers.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Photo Module</servlet-name>
<url-pattern>/Photos</url-pattern>
</servlet-mapping>
The src of the HTML <img> element should just point to an URL. An URL is a web address like as the one you enter in your browser address bar. Servlets can be mapped on certain URL patterns by web.xml so that when you invoke an URL which matches the servlet mapping, that the servlet will be invoked. See also our Servlets Wiki.
You have mapped the servlet on an URL pattern of /Photos. Entering an URL like
http://localhost:8080/YourContextPath/Photos
in the browser address bar should display the image. So basically, assuming that the JSP runs in the same context path, this should do:
<img src="Photos" />
Or when you want to make it relative to the domain root, then you need to include the context path dynamically:
<img src="${pageContext.request.contextPath}/Photos" />
Said that, there are some problems in your servlet. You haven't set the content type header. This way the browser won't know what to do with the HTTP response. It'll display a Save As popup when you enter its URL straight in address bar and it'll display nothing when you call it in <img>. If it's a JPG image, then add the following line before you call response.getOutputStream().
response.setContentType("image/jpeg");
This way the browser understands that it's a JPG image and it'll display it as such. See also the blog which you linked for the proper way of setting the headers.
Another problem is that you're calling request.getSession(false) which can potentially return null when there's no means of a session. But you are not checking for that on the next line! So either use
HttpSession session = request.getSession();
so that it is never null, or add a
if (session == null) {
// Display some default image or return a 404 instead.
return;
}
You would like to do the same for userId and photoStream. If it's absent, then display a default image or return a 404.
Attach your web.xml to see how you are (if you are at all) mapping your servlet, so we can give you the URL.
web.xml is the way to tie URLs with the servlets.
Your way with buffered output towards Servlet output stream is IMHO a correct and good way of writing data to output. It would be better to use Filter to cache output though instead of writing the response all the time.
UPDATE:
Based on the blog you mentioned as source and web.xml in it, the correct url should be
<img src="/image/my_image.jpg" />
where my_image.jpg is a sample name of uploaded image.
If you register your serlvet for the pattern /Photos
<img src="/yourContextRoot/Photos" />
I know this has probably been asked 10000 times, however, I can't seem to find a straight answer to the question.
I have a LOB stored in my db that represents an image; I am getting that image from the DB and I would like to show it on a web page via the HTML IMG tag. This isn't my preferred solution, but it's a stop-gap implementation until I can find a better solution.
I'm trying to convert the byte[] to Base64 using the Apache Commons Codec in the following way:
String base64String = Base64.encodeBase64String({my byte[]});
Then, I am trying to show my image on my page like this:
<img src="data:image/jpg;base64,{base64String from above}"/>
It's displaying the browser's default "I cannot find this image", image.
Does anyone have any ideas?
Thanks.
I used this and it worked fine (contrary to the accepted answer, which uses a format not recommended for this scenario):
StringBuilder sb = new StringBuilder();
sb.append("data:image/png;base64,");
sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(imageByteArray, false)));
contourChart = sb.toString();
According to the official documentation Base64.encodeBase64URLSafeString(byte[] binaryData) should be what you're looking for.
Also mime type for JPG is image/jpeg.
That's the correct syntax. It might be that your web browser does not support the data URI scheme. See Which browsers support data URIs and since which version?
Also, the JPEG MIME type is image/jpeg.
You may also want to consider streaming the images out to the browser rather than encoding them on the page itself.
Here's an example of streaming an image contained in a file out to the browser via a servlet, which could easily be adopted to stream the contents of your BLOB, rather than a file:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
ServletOutputStream sos = resp.getOutputStream();
try {
final String someImageName = req.getParameter(someKey);
// encode the image path and write the resulting path to the response
File imgFile = new File(someImageName);
writeResponse(resp, sos, imgFile);
}
catch (URISyntaxException e) {
throw new ServletException(e);
}
finally {
sos.close();
}
}
private void writeResponse(HttpServletResponse resp, OutputStream out, File file)
throws URISyntaxException, FileNotFoundException, IOException
{
// Get the MIME type of the file
String mimeType = getServletContext().getMimeType(file.getAbsolutePath());
if (mimeType == null) {
log.warn("Could not get MIME type of file: " + file.getAbsolutePath());
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mimeType);
resp.setContentLength((int)file.length());
writeToFile(out, file);
}
private void writeToFile(OutputStream out, File file)
throws FileNotFoundException, IOException
{
final int BUF_SIZE = 8192;
// write the contents of the file to the output stream
FileInputStream in = new FileInputStream(file);
try {
byte[] buf = new byte[BUF_SIZE];
for (int count = 0; (count = in.read(buf)) >= 0;) {
out.write(buf, 0, count);
}
}
finally {
in.close();
}
}
If you don't want to stream from a servlet, then save the file to a directory in the webroot and then create the src pointing to that location. That way the web server does the work of serving the file. If you are feeling particularly clever, you can check for an existing file by timestamp/inode/crc32 and only write it out if it has changed in the DB which can give you a performance boost. This file method also will automatically support ETag and if-modified-since headers so that the browser can cache the file properly.