0

Before display, i have inserted BLOB to MYSQL and success. I used this code to display BLOB to JSP.

        Connection con = Koneksi.getKoneksi();
        String id = request.getParameter("id_pengurus");
        PreparedStatement ps = con.prepareStatement("select foto from pengurus where idpengurus = ?");
        ps.setString(1, id);
        ResultSet rs = ps.executeQuery();
        rs.next();
        Blob b = rs.getBlob("foto");
        response.setContentType("image/jpg");
        response.setContentLength((int) b.length());
        InputStream is = b.getBinaryStream();
        OutputStream os = response.getOutputStream();
        byte buf[] = new byte[(int) b.length()];
        is.read(buf);
        os.write(buf);
        os.close();

When I use this code to display BLOB in SQL to JSP, it was worked. When I use this code to display BLOB in MYSQL to JSP, it didn't work. What solution should i do? Sorry for my bad English. Thanks before.

Martin
  • 1
  • 1
    I don't understand the question but you shouldn't be closing the stream you haven't opened (nothing to do with the problem and more of a general rule). – serg.nechaev Aug 16 '16 at 02:15
  • sorry before sir. I used that code in JSP to display BLOB in ORACLE SQL. Is it possible that code for display blob SQL and mysql different? Thanks – Martin Aug 16 '16 at 02:38
  • You never check how many bytes were read when you called `is.read(buf)`, so you may not have received everything. If you're going to just get the entire BLOB as a byte array, your should just call `byte[] buf = rs.getBytes("foto")` and forget about the `Blob` class. – Andreas Aug 16 '16 at 02:41
  • I have solved my problem sir Andreas. Just change Blob IMPORT from SQL to MYSQL and it can display image now. Thanks! – Martin Aug 16 '16 at 03:11

1 Answers1

0

Blob is binary content and JSP is text/html. Which means you can not combine them, however if you are asking about how to serve the image using JSP/Servlet then you can do it by writing it's content to the output stream of the response, make sure to set proper headers Content-Type: image/png or something like that in the response.

You can have two JSP files. One for serving image content and other to display it.

In the second JSP a simple <img> tag would do the trick.

<img src="/imagejsp.jsp"/>

This would display the image.

11thdimension
  • 10,333
  • 4
  • 33
  • 71
  • Thank you sir11thdimension for your answer. How to change from binary to byte sir? i have tried in this link http://stackoverflow.com/questions/11192020/display-blob-image-through-jsp, but i can't understand sir. Sorry before. Thanks – Martin Aug 16 '16 at 02:37
  • I have solved my problem sir. Just change Blob IMPORT from SQL to MYSQL and it can display image now. Thanks a lot for your advice! – Martin Aug 16 '16 at 03:14