我可以将图像作为 byte[] 获取并使用 form.jsp 和 FormFile 将其存储在我的数据库中。现在我需要能够检索该 byte[] 并将其作为图像显示在 JSP 中。有没有办法创建资源并检索该图像?
问问题
2494 次
2 回答
1
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;
}
写入tempByte
into stream
,刷新并关闭它。return null
从动作。
现在从内部调用动作<img src="yourAction.do">
于 2012-08-21T12:45:13.467 回答
0
<%@ 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();
}
%>
通过这个你可以从数据库中检索图像
于 2012-08-21T12:48:29.250 回答