[Logo]
Forums Register Login
Putting an image on JSP
How can I put an image from database (byte[]) on a jsp page? If somedoby have the surce code please post.

PS: I'm using struts, I found the tag <html:img> but I need to show the image without write an .jpg file on my hard-disk, like dymanic images.
Please remember that every image on a web page is the result of a separate request to the web server. You can't mix the text of a web page with the binary data of an image. There have been MANY discussions in this forum - you should use a servlet to handle requests for binary data.
Bill
I can point you in the direction of one solution:

<img src="http://myapp/.getimage?img_code=123">

Create a servlet and map "*.getimage" to it in the web.xml file of your web application. Because struts normally looks for "*.do" it should not interfere with struts:

<servlet>
<servlet-name>getImage</servlet-name>
<servlet-class>com.myapp.GetImage</servlet-class><!-- the fully qualified classname of your servlet -->
</servlet>
<servlet-mapping>
<servlet-name>getImage</servlet-name>
<url-pattern>*.getimage</url-pattern>
</servlet-mapping>

in the doPost(..) method of your servlet, set the content type (where you would normally use "text/html") to "image/gif":


public class GetImage extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("image/gif");
PrintWriter out = response.getWriter();

/* read your image from the database, and use the PrintWriter to
write it to the response
*/
out.close();
}

}

You can find a list of subtypes here for your specific format.
 

Originally posted by Scheepers de Bruin:

/* read your image from the database, and use the PrintWriter to
write it to the response
*/



Did you mean "use ServletOutputStream to write it to the response"?

PrintWriter is for text.

http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletOutputStream.html
http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintWriter.html
I actually meant response.getOutputStream(), and then use ImageIO...

Tx for pointing it out.

This thread has been viewed 1279 times.

All times above are in ranch (not your local) time.
The current ranch time is
Sep 24, 2018 07:04:28.