Rahul P
Rahul P

Reputation: 1103

Displaying an image in a jsp from a byte array using struts

I can get an image as a byte[] and store it in my database using form.jsp and FormFile. Now I need to be able to retrieve that byte[] and display it back in the JSP as an image. Is there a way to create a resource and retrieve that image?

Upvotes: 0

Views: 2556

Answers (2)

Sreenath S
Sreenath S

Reputation: 1269

public ActionForward pageLoad(ActionMapping a,ActionForm b,HttpServletRequest c,HttpServletResponse d){
    b.setImageData(loadImageData());
    return a.findForward("toPage");
}

public ActionForward imageLoad(ActionMapping a,ActionForm b,HttpServletRequest c,HttpServletResponse d){
    byte[] tempByte = b.getImageData();
    d.setContentType("image/jpeg");
    ServletOutputStream stream = d.getOutputStream();
    /*
        Code to write tempByte into stream here.
    */
    return null;
}

Write the tempByte into stream, flush and close it. return null from the action.

now call the action from inside an <img src="yourAction.do">

Upvotes: 1

Aravind
Aravind

Reputation: 1065

       <%@ page import="java.sql.*" %>
       <%@ page import="java.io.*" %> 

        Connection connection =  null;

      String connectionURL = "jdbc:mysql://localhost:3306/Test";
      ResultSet rs = null;

       PreparedStatement psmnt = null;

 InputStream sImage;
 try {

Class.forName("com.mysql.jdbc.Driver").newInstance();

 connection = DriverManager.getConnection(connectionURL, "Admin", "Admin");
psmnt = connection.prepareStatement("SELECT image FROM save_image WHERE id = ?");
psmnt.setString(1, "11"); // here integer number '11' is image id from the table
rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
 }
 }
 }
     catch(Exception ex){
           out.println("error :"+ex);
        }
            finally {
                  rs.close();
                 psmnt.close();
                 connection.close();
         }
                  %> 

By this u can retrive Image from Database

Upvotes: 0

Related Questions