How to Retrieve and Display Images from a Database in a Jsp Page

I want to retrieve image from the database and display it in a jsp page

Suppose you have jsp page where you want to retreive image . you can do something like this to retrieve any image from database.

 <%   //dbconnection
try {
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","");
Statement statement = conn.createStatement() ;
resultSet=statement.executeQuery("select * from tablename") ;
%>
<% while(resultSet.next()){ %>

Image - <img src="ImageProcess?id=<%=resultSet.getString("id")%>" width="20%"/>

<%
}
}catch(Exception e){}

%>

In Above code this -> <img src="ImageProcess?id=<%=resultSet.getString("id")%>" />line is important ,here you are passing parameter to servlet to get particular image

Now,in your servleti.e ImageProcess you have to retreive the id in doGet and pass in query ,lastly send back the reponse to jsp page .

Blob image = null;
byte[] imgData = null;
String id= request.getParameter("id");//here you are getting id
int i;
ResultSet rs =null;

try {

//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","");


String sql = "SELECT image FROM tablename where id=?"; //here pass that id in query to get particular image

PreparedStatement ps = con.prepareStatement(sql);


ps.setString(1, id);
rs = ps.executeQuery();
while (rs.next()) {
image = rs.getBlob("image");//getting image from database
imgData = image.getBytes(1,(int)image.length()); //extra info about image
}

response.setContentType("image/gif");//setting response type



OutputStream o = response.getOutputStream();

o.write(imgData);//sending the image to jsp page
o.flush();
o.close();


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

}

Also this is not complete code,make changes as per your requirements .also don't forget to add jar's file

how to display an image from mysql database on a jsp page?

why dont you try like this:

  1. i have a getImageDetails.jsp to retrive the image data from the database based on user_id or name or some other constraint as follows (put the code in jsp/servlet page)

    int img_id = Integer.parseInt(request.getParameter("your_id"));
    Connection con = //get your connection object here ;
    ResultSet rs = null;
    PreparedStatement pstmt = null;
    OutputStream oImage;
    try {
    pstmt = con.prepareStatement("your sql statement for retriving the image column data");
    pstmt.setInt(1, img_id);
    rs = pstmt.executeQuery();
    if(rs.next()) {
    byte barray[] = rs.getBytes(1);
    response.setContentType("image/gif");
    oImage=response.getOutputStream();
    oImage.write(barray);
    oImage.flush();
    oImage.close();
    }
    }
    catch(Exception ex){
    //ex.printStackTrace();
    }finally {
    try{
    if(con!=null)
    con.close();
    }catch(Exception ex){
    // ex.printStackTrace();
    }
    }
  2. then i am calling this page from html or any another jsp page as follows

    < img src="getImageDetails.jsp?your_id=12" width="50" height="50" />

please try like this you will get answer

let me know the status
happy coding

Displaying image in jsp from database

You have closed your connection before recieving the image itself
Change your code to

 <html>
<body>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="com.mysql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="javax.servlet.http.HttpSession"%>
<%@ page language="java"%>
<%@ page session="true"%>
<%@ page import="java.sql.*"%>
<%
Blob image = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String iurl1=null;

try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:portnumber/dbname","","");
stmt = con.createStatement();
rs = stmt.executeQuery("select * from tablename where id = 1");%>
<table border="2">
<tr><th>DISPLAYING IMAGE</th></tr>
<tr><td>Image 2</td></tr>
<tr><td>
<%while(rs.next()){%>
<img src="<%=rs.getString("image") %>" width="500" height="500"/>
<%}%>
</td></tr>
</table>
<%}
catch (Exception e) {
out.println("DB problem");
return;
}
finally {
try {
rs.close();
stmt.close();
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
%>
</body>
</html>

Or else a better way save it in a variable

 <html>
<body>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="com.mysql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="javax.servlet.http.HttpSession"%>
<%@ page language="java"%>
<%@ page session="true"%>
<%@ page import="java.sql.*"%>
<%
Blob image = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String iurl1=null;
String image=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:portnumber/dbname","","");
stmt = con.createStatement();
rs = stmt.executeQuery("select * from tablename where id = 1");
while(rs.next()){
image = rs.getString("image");
}
}
catch (Exception e) {
out.println("DB problem");
return;
}
finally {
try {
rs.close();
stmt.close();
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
%>
<table border="2">
<tr><th>DISPLAYING IMAGE</th></tr>
<tr><td>Image 2</td></tr>
<tr><td>
<img src="<%=image %>" width="500" height="500"/>
</td></tr>
</table>

</body>
</html>

How to retrieve image from database and display in JSP via Servlet?

The src of the HTML <img> element should just point to an URL. An URL is a web address like as the one you enter in your browser address bar. Servlets can be mapped on certain URL patterns by web.xml so that when you invoke an URL which matches the servlet mapping, that the servlet will be invoked. See also our Servlets Wiki.

You have mapped the servlet on an URL pattern of /Photos. Entering an URL like

http://localhost:8080/YourContextPath/Photos

in the browser address bar should display the image. So basically, assuming that the JSP runs in the same context path, this should do:

<img src="Photos" />

Or when you want to make it relative to the domain root, then you need to include the context path dynamically:

<img src="${pageContext.request.contextPath}/Photos" />

Said that, there are some problems in your servlet. You haven't set the content type header. This way the browser won't know what to do with the HTTP response. It'll display a Save As popup when you enter its URL straight in address bar and it'll display nothing when you call it in <img>. If it's a JPG image, then add the following line before you call response.getOutputStream().

response.setContentType("image/jpeg");

This way the browser understands that it's a JPG image and it'll display it as such. See also the blog which you linked for the proper way of setting the headers.

Another problem is that you're calling request.getSession(false) which can potentially return null when there's no means of a session. But you are not checking for that on the next line! So either use

HttpSession session = request.getSession();

so that it is never null, or add a

if (session == null) {
// Display some default image or return a 404 instead.
return;
}

You would like to do the same for userId and photoStream. If it's absent, then display a default image or return a 404.

Display image (from database) in JSP

I think you have a little more work to do to get this going. The img<> tag expects a URL, and cannot magically convert a database blob or similar to a URL.

My approach would be:

  • Create a servlet that serves thumbnail images from the database, and publishes URLs like /myApp/product/thumbnails?productId=12345
  • Test your servlet from a browser
  • Change your JSP to create these URLs.

Good luck.



Related Topics



Leave a reply



Submit