JDBC儲存和讀取位元據,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(); } } } }%>
讀取二進位檔案
<%out.clear(); //清空一切輸出int id=Integer.parseInt(request.getParameter("id")); //擷取附件ID Connection 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();} %>