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(); } %>
本文由用户 n672 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!