从网上查了许多资料,攒了个功能,暂且记下来,呵呵。需要apache的fileupload组件和io组件。
// 建立一个新的Upload对象
DiskFileUpload upload = new DiskFileUpload();
upload.setSizeThreshold(1024 * 300); //设置缓冲区大小
String rootPath = getServletConfig().getServletContext().getRealPath("/");
upload.setRepositoryPath(rootPath+"//uploads");//设置缓冲区目录upload.setSizeMax(10*1024*1024); //限制最大文件为10MB FileItem item = null;Connection conn = null; ResultSet rst = null;PreparedStatement pstmt = null;OutputStream output = null;BufferedInputStream bi = null;try{ List items = upload.parseRequest(request); Iterator iter = items.iterator(); while(iter.hasNext()){ item = (FileItem) iter.next(); if (!item.isFormField()){//(不是表单域)是文件对象 bi = new BufferedInputStream(item.getInputStream()); byte[] buffer = new byte[1024]; conn = JdbcUtilsHelper.getConnection(); conn.setAutoCommit(false); //先清空原来的上传文件 pstmt = conn.prepareStatement("update table set col=EMPTY_BLOB() where id=?"); pstmt.setString(1, xh); pstmt.execute(); pstmt.close(); pstmt = conn.prepareStatement("select col from table where id=? for update"); pstmt.setString(1, xh); rst = pstmt.executeQuery(); if(rst.next()){ System.out.println("next"); oracle.sql.BLOB blob = (oracle.sql.BLOB)rst.getBlob(1); output = blob.setBinaryStream(0); int readNum = -1; while( (readNum = bi.read(buffer)) != -1){ //通过Oracle驱动使用流方式读写 output.write(buffer,0,readNum); } //BLOB字段输出流关闭,以及其他GC处理 bi.close(); output.flush(); output.close(); conn.commit(); rst.close(); item.delete(); } conn.setAutoCommit(true); } }// end while rtnCode = "1";//保存成功}catch(FileUploadException e) {// 处理文件尺寸过大异常 if(e instanceof SizeLimitExceededException) { rtnCode = "-2";//文件太大 } e.printStackTrace(); }catch(Exception e){ rtnCode = "-1";//保存失败 e.printStackTrace();}finally{ if(rst != null){ try{ rst.close(); }catch(Exception e1){ e1.printStackTrace(); } } if(pstmt != null){ try{ pstmt.close(); }catch(Exception e1){ e1.printStackTrace(); } } if(conn != null){ conn.setAutoCommit(true); try{ conn.close(); }catch(Exception e1){ e1.printStackTrace(); } } if(item != null){ item.delete(); } }// end finally