/** */ /** * 下载:从数据库中读出blob字段的内容,并下载 * @param response * @param file_name */ public static void downloadFromDb( HttpServletResponse response, long accessoryId // 附件ID ) ... { BufferedInputStream in = null; BufferedOutputStream out= null; try...{ CustomAccessoryBase cab=CustomAccessoryBase.getObjectById(accessoryId); java.sql.Blob blob =cab .getContent(); //附件内容 String cname=cab.getAccessoryName(); //附件名称 cname = new String(cname.getBytes("GBK"),"iso8859-1"); response.reset(); response.setHeader("Content-Disposition", "attachment;"+" filename="+cname); in = new BufferedInputStream( blob.getBinaryStream()); out = new BufferedOutputStream(response.getOutputStream()); byte[] buffer =new byte[1024]; int len = 0 ; while ((len = in.read(buffer))!=-1) ...{ out.write(buffer,0,len); } out.flush(); }catch(Exception e)...{ e.printStackTrace(); }finally...{ try...{ if ( in != null ) in.close(); }catch(Exception e)...{ } try...{ if ( out != null ) out.close(); }catch(Exception e)...{ } } } /** */ /** * 把附件保存到表中的方法 * @param iFilePath */ public static void testBlob(String iFilePath) ... { Session s = null; byte[] buffer = new byte[1]; buffer[0] = 1; try ...{ SessionFactory sf = ZAutoLoadServlet.getSessionFactory(); s = sf.openSession(); Transaction tx = s.beginTransaction(); CustomAccessoryBase cab=new CustomAccessoryBase(); cab.setContent(Hibernate.createBlob(buffer)); s.save(cab); s.flush(); s.refresh(cab, LockMode.UPGRADE); BLOB blob = (BLOB) cab.getContent(); OutputStream out = blob.getBinaryOutputStream(); File f = new File(FileUpload.getStorageHome()+iFilePath); FileInputStream fin = new FileInputStream(f); int count = -1, total = 0; byte[] data = new byte[(int) fin.available()]; fin.read(data); out.write(data); fin.close(); out.close(); s.flush(); tx.commit(); } catch (Exception e) ...{ System.out.println(e.getMessage()); } finally ...{ if (s != null) try ...{ s.close(); } catch (Exception e) ...{ } } }