Display image in img tag stored as BLOB in database

浪子不回头ぞ 提交于 2019-12-11 19:45:46

问题


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)


回答1:


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.




回答2:


As mthmulders said what you are seeing is the the value of Blob.toString().

BalusC posted sometime ago a 2 great articles on serving images recpvered from a database blog through a servlet :

http://balusc.blogspot.fr/2007/04/imageservlet.html

And a more recent one with GZIP and resume handling

http://balusc.blogspot.fr/2009/02/fileservlet-supporting-resume-and.html



来源:https://stackoverflow.com/questions/15833184/display-image-in-img-tag-stored-as-blob-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!