Search code examples
javablobjava-web-start

Display image in img tag stored as BLOB in database


I can't display BLOB image that I have in mysql saved. I have beans, jsp. I use 3multy-tier architecture, I want to display all the products with the picture.

In acceesor:

 try {
        Connection cn = getVla().getConnection();
        String sql = "SELECT * FROM products";
        PreparedStatement pst = cn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();
        ArrayList<products> ls = new ArrayList<products>();
        while(rs.next()) {
            products s = new products();
            s.setPk(rs.getLong("pk"));
            s.setName(rs.getString("name"));
            s.setPrice(rs.getDouble("price"));
            s.setPic(rs.getBlob("pic"));
            s.setComments(rs.getString("comments"));
            ls.add(s);
        }
        return ls;
    }

In products:

 public Blob getPic() {
        return pic;
    }

In main.jsp

<%=
List<products> product = bean.getproducts();

%>
<h1>Product: </h1>
<%  
for(products c : product) { 
%>
From <%= c.getName()%> <br/>
<%= c.getPic()%></b><br/>
<b><%= c.getPrice()%> </b><br/>
<%= c.getComments()%>
<hr/>
<%
}
%>

How I can display the picture? (Currently I am getting com.mysql.jdbc.Blob@2e5f6a64 in display)


Solution

  • What you're seeing is the result of Blob.toString(). Since it's binary content, the JVM cannot really figure a nice representation.

    What you should do is create a seperate Servlet that only retrieves the Blob from the database and streams its content to response.getOutputStream(). In your JSP, you add an <img> tag whose src-attribute points to the Servlet you just wrote.

    The Servlet should read the image for one product at a time, so the query would be slightly different: it should be enough to have

    String sql = "SELECT pic FROM products where pk = " + pk;
    

    Note that you need to specify this pk variable using some request parameter. The above line of code is just an example to demonstrate the idea. It is very unsafe to literally copy a request URL into an SQL query. Google for "SQL Injection" to read more about that.

    Using Blob.getInputStream() you can obtain an InputStream whose contents you could copy to response.getOutputStream() in order to write it back to the browser. Don't forget to set the appropriate content-type on that response, for example "image/jpg" in case of JPEG pictures.