此文接上篇 主要想讲一下图片的下载
框架背景 :spring + hibernate
看代码 ok 走你
1 public void getDate(HttpServletRequest request, HttpServletResponse response,String id) throws Exception { 2 Connection conn = null; 3 PreparedStatement ps =null; 4 ResultSet rs = null; 5 response.reset(); 6 //response.setContentType("image/*;charset=GBK"); 7 //response.setContentType("image/jpeg"); 8 //response.setContentType("text/html; charset=GBK"); 9 response.setContentType("unknown"); 10 11 try{ 12 conn = DataSourceUtils.getConnection(jdbcTemplate.getDataSource()); 13 String sql = "select img,msg,filename from "+tableName+" where id = " +"'"+id+"'"; 14 System.out.println(sql); 15 ps = conn.prepareStatement(sql); 16 rs = ps.executeQuery(); 17 if(rs.next()){ 18 Blob blob = rs.getBlob("img"); 19 String name=rs.getString("filename"); 20 response.addHeader("content-disposition", "attachment;filename=\"" + name+"\""); 21 //response.setContentType("application/x-download"); 22 //response.setContentType("application/x-msdownload"); 23 //response.addHeader("Content-Disposition","attachment;filename="+clmc+"."+cllx); 24 InputStream pi = blob.getBinaryStream(); 25 OutputStream sos = response.getOutputStream(); 26 byte bytes[] = new byte[(int)((BLOB)blob).length()]; 27 for(int n = 0; (n = pi.read(bytes)) != -1;)sos.write(bytes, 0, n); 28 pi.close(); 29 sos.flush(); 30 } 31 }catch(Exception ex){ 32 DataSourceUtils.releaseConnection(conn, jdbcTemplate.getDataSource()); 33 throw new Exception("执行时出错!" + ex.getMessage()); 34 }finally{ 35 if(rs!=null)rs.close(); 36 if(ps!=null)ps.close(); 37 if(conn!=null){ 38 try{ 39 DataSourceUtils.releaseConnection(conn,jdbcTemplate.getDataSource()); 40 }catch(Exception ex){ 41 ex.printStackTrace(); 42 } 43 } 44 } 45 }
看完之后你会发现 其实很简单
就是 用
response.addHeader("content-disposition", "attachment;filename=\"" + name+"\"");
嗯
下一篇可能要学一下 request 和 respones 的一些讲解(当然也是来自网络的资源我是小白 自己做好 学习笔记就好 )