0

I'm trying to display a image which comes from the database as a blob image. this is my servlet code to display the image

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
    PrintWriter out = response.getWriter();

    String name = request.getParameter("name");
    Blob image = null;
    byte[] imgData = null;
    Statement stmt = null;
    ResultSet rs = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users", "root", "");

        stmt = con.createStatement();
        rs = stmt.executeQuery("select photo from details where name='" + name + "'");

        String imgLen = "";
        while (rs.next()) {
            imgLen = rs.getString(1);
        }
        rs = stmt.executeQuery("select photo from details where name='" + name + "'");
        if (rs.next()) {
            
            out.println("\n");
            out.println("Getting blob");
            Blob blob = rs.getBlob(1);
            out.println("Reading image");
            BufferedImage img = ImageIO.read(blob.getBinaryStream());
            out.println("img = " + img);
            
    } catch (Exception e) {
        out.println("Unable To Display image");
        out.println("Image Display Error");
        return;
    } finally {
        try {
            rs.close();
            stmt.close();
            //con.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

but this code only give the details about the image, not the exact image. How can I display the real image?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • it is better to path of image in database rather than image. Store your image on server(your machine's local disk) and store path of this image in db.It will be more fast –  Sep 01 '17 at 05:40
  • yes it works at any situation I have done it before :) but I wanna try this one too ;) – upeksha silva Sep 04 '17 at 05:17

0 Answers0