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));
Image image = imageDAO.find(imageId);
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 .