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?
2 Answers
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">
3 Comments
Rahul P
thanks. i need to write separate action for that. Or actually I have action where I'm bringing all data with image also. So for image i do need to write separate action
Rahul P
could you please write full example of this in DispatchAction
Sreenath S
Check now. This is just how the code looks like, an abbreviation.
<%@ 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