JDBC存儲和讀取二進制數據
以下JSP文件用common-fileupload組件實現文件上傳,并將文件以二進制文件的形式存入數據庫
<%
if("POST".equalsIgnoreCase(request.getMethod)){//如果是POST表單
DiskFileUpload diskFileUpload = newDiskFileUpload();
diskFileUpload.setHeaderEncoding("UTF-8");//設置編碼
//解析上傳的數據
List <FileItem> list =diskFileUpload.parseRequest(request);for(FileItem fileItem : list){ if(!fileItem.isFormField()){ //如果是文件域 //文件路徑,替換掉特殊字符 String filename =fileItem.getName().replace("\\","/"); //獲取文件名 filename =filename.substring(filename.lastIndexOf("/")+1); //獲取文件類型 String filetype =fileItem.getContentType(); //獲取文件大小 Int filesize =fileItem.getSize(); Connection conn = null; PrepareStatement preStmt = null; try{ conn = DbManager.getConnection(); preStmt = conn.prepareStatement( "insert into table_name (filename,filetype,size,content,date) values(?,?,?,?,?)"); preStmt.setString(1,filename); preStmt.setString(2,filetype); preStmt.setInt(3,filesize); preStmt.setBinaryStream(4,fileItem.getInputStream(),filesize); preStmt.setTimestamp(5,newTimestamp(System.currentTimeMills())); preStmt.executeUpdate(); }finally{ if(preStmt != null) preStmt.close(); if(conn != null) conn.close(); } } } } %> </pre><br />
讀取二進制文件
<%
out.clear(); //清空一切輸出
int id=Integer.parseInt(request.getParameter("id")); //獲取附件IDConnection conn= null; PrepareStatementpreStmt = null; ResultSet rs =null; try{ conn =DbManager.getConnection(); preStmt =conn.prepareStatement("select from table_name where id = ?"); preStmt.setInt(1,id); rs =preStmt.executeQuery(); if(rs.next()){ response.reset(); //重置response response.setContentType(rs.getString("fileType"));//設置輸出的文件類型 response.setContentLength(ra.getInt("filesize"));//設置輸出的文件長度 InputStream ins = null; OutputStream ous = null; try{ ins = rs.getBinaryStream("content"); ous = response.getOutputStream(); byte [] b = new byte[1024]; int len = 0; while((len = ins.read(b)) !=-1){ ous.write(b,0,len); } }finally{ if(ous != null) ous.close(); if(ins != null) ins.close(); } }else{ out.println("沒有找到附件:"+id); } }finally{ if(rs! = null) rs.close(); if(preStmt != null) preStmt.close(); if(conn != null) conn.close(); } %> </pre><br />
本文由用戶 n672 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!