How to load image from database inside JSF page using managed beans?

I have a database with some images. Can someone explain to me how to upload an image on a JSF page?

I already have a managed bean that converts an Image object to streamcontent. This streamcontent is called from the page in the tag <h:graphicImage>, but when I check the source code of the page, there is no srcwhere the image can be uploaded.

+5
source share
1 answer

JSF <h:graphicImage>gets rendered as an HTML element <img>. Its attribute srcshould point to the URL, not the binary content. Thus, you must save the URL (or at least some identifier as the request parameter or pathinfo) in the JSF bean and create a separate servlet to stream the image from the database to the HTTP response.

Use this on the JSF page:

<h:graphicImage value="images/#{bean.imageId}">

Assuming it bean.getImageId()returns 123, this is rendered in HTML as:

<img src="images/123">

Create a class Servletthat maps to web.xmlon url-patternfrom /images/*and implements its method doGet()as follows:

Long imageId = Long.valueOf(request.getPathInfo().substring(1)); // 123 (PS: don't forget to handle any exceptions).
Image image = imageDAO.find(imageId); // Get Image from DB.
// Image class is just a Javabean with the following properties:
// private String filename;
// private Long length;
// private InputStream content;

response.setHeader("Content-Type", getServletContext().getMimeType(image.getFilename()));
response.setHeader("Content-Length", image.getLength());
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getFilename() + "\"");

BufferedInputStream input = null;
BufferedOutputStream output = null;

try {
    input = new BufferedInputStream(image.getContent());
    output = new BufferedOutputStream(response.getOutputStream());
    byte[] buffer = new byte[8192];
    int length;
    while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
} finally {
    if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
    if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}

In ImageDAO#find()you can use ResultSet#getBinaryStream()for images both InputStreamfrom the database.

An extended example can be found in this article .

+12

All Articles