java - Display image in img tag stored as BLOB in database -
i can't display blob
image have in mysql
saved. have beans, jsp. use 3multy-tier architecture, want display products picture.
in acceesor:
try { connection cn = getvla().getconnection(); string sql = "select * 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) { %> <%= c.getname()%> <br/> <%= c.getpic()%></b><br/> <b><%= c.getprice()%> </b><br/> <%= c.getcomments()%> <hr/> <% } %>
how can display picture? (currently getting com.mysql.jdbc.blob@2e5f6a64 in display)
what you're seeing result of blob.tostring()
. since it's binary content, jvm cannot figure nice representation.
what should create seperate servlet retrieves blob
database , streams content response.getoutputstream()
. in jsp, add <img>
tag src
-attribute points servlet
wrote.
the servlet
should read image 1 product @ time, query different: should enough have
string sql = "select pic products pk = " + pk;
note need specify pk
variable using request parameter. above line of code example demonstrate idea. very unsafe literally copy request url sql query. google "sql injection" read more that.
using blob.getinputstream()
can obtain inputstream
contents copy response.getoutputstream()
in order write browser. don't forget set appropriate content-type
on response, example "image/jpg" in case of jpeg pictures.
Comments
Post a Comment