Not displaying image from database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chintapallysand
    New Member
    • May 2014
    • 1

    Not displaying image from database

    Code:
    <%@ page import="java.sql.*" %>
    <% Class.forName("com.mysql.jdbc.Driver"); %>
    <HTML>
        <HEAD>
            <TITLE>Fetching Data From a Database</TITLE>
        </HEAD>
        <BODY>
            <H1>Fetching Data From a Database</H1>
            <% 
      
    response.setContentType("image/jpg");
     
    
     
     Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","srys");
                Statement statement = connection.createStatement();
                String id = request.getParameter("id");  
    ResultSet resultset = statement.executeQuery("select file_data from file where id = '" + id + "'") ; 
                if(!resultset.next()) {
                    out.println("Sorry, could not find that publisher. ");
                } else {
            %>
            <TABLE BORDER="1">
                <TR>
                    
                   <TH>picture</TH>
               </TR>
               <TR>
                    
                   <TD> <%= resultset.getBlob(1) %> </TD>
               </TR>
           </TABLE>
           <BR>
           <% 
               } 
           %>
        </BODY>
    </HTML>
    Last edited by Rabbit; May 14 '14, 03:29 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Do not mix content of different types within a single response. Either send only the binary data for the image (contentType = image/jpg) or only send the HTML tags(contentTyp e =text/html).

    In your case you send HTML-text bytes (with embedded image data bytes), but tell the browser (by setting the content type) to interpret all the data as an image. Of course this does not work, because an image has a special structure and the browser sees that the data does not fit to the structure, so it displays an error or does nothing.

    Send the embedding HTML page first without image data, but with an image tag instead that should contain an URL. When the browser renders the HTML page it fires a second request with this URL automatically and then you send over the image data only.

    Comment

    Working...