向mysql插入图片是通过二进制输入流的形式实现的,就是pstmt.setBinaryStream(2,str,str.available());存储在数据库longblob数据类型里面。以上这些已经实现。
接着我想从数据库里面取出数据,并在页面显示图片,以下是部分代码:
public class DBResult {
public static InputStream outImage(Connection conn,String picid) {
int id=Integer.parseInt(picid);
String sql="select pic from p where picid="+id;
PreparedStatement pstmt = null;
ResultSet rs=null;
InputStream is = null;
try{
pstmt = (PreparedStatement) conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
is = rs.getBlob("pic").getBinaryStream();
}
is.close();
rs.close();
pstmt.close();
}catch (Exception e) {
e.printStackTrace();// TODO: handle exception
}
return is;
}
}
然后我调用这个类到servlet里面,以便输出图片到页面imageout.jsp,以下是部分servlet代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf8");
response.setCharacterEncoding("utf8");
String page=null;
String picid = request.getParameter("txtpicid");
if(picid!=null){
response.setContentType("image/jpeg");
Connection conn = dataBase.getConnection();
InputStream is=DBResult.outImage(conn, picid);
if(is!=null){
try{
is=new BufferedInputStream(is);
BufferedImage bi=ImageIO.read(is);
OutputStream os=response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(bi);
is.close();
os.close();
}catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
request.setAttribute("picid", picid);
page="imageout.jsp";
response.sendRedirect(page);
}
以下是imageout.jsp页面的路径设置:
<img src="http://localhost:8080/send-app/ImageOutServlet" width="400" height="300"/>
然后问题是,当程序运行到ImageOutServlet时,可以显示图片,但在控制台有以下错误提示:
十一月 16, 2012 5:17:13 下午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [ImageOutServlet] in context with path [/send-app] threw exception
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:483)
at dbconn.servlet.ImageOutServlet.doPost(ImageOutServlet.java:58)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)