在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

JDBC存储和读取二进制数据

2016-12-20 13:12| 发布者: zhangjf| 查看: 453| 评论: 0

摘要: 以下JSP文件用common-fileupload组件实现文件上传,并将文件以二进制文件的形式存入数据库 % if(POST.equalsIgnoreCase(request.getMethod)){//如果是POST表单 DiskFileUpload diskFileUpload = ...

以下JSP文件用common-fileupload组件实现文件上传,并将文件以二进制文件的形式存入数据库

  1. <%
  2. if("POST".equalsIgnoreCase(request.getMethod)){//如果是POST表单
  3. DiskFileUpload diskFileUpload = newDiskFileUpload();
  4. diskFileUpload.setHeaderEncoding("UTF-8");//设置编码
  5. //解析上传的数据
  6. List <FileItem> list =diskFileUpload.parseRequest(request);
  7. for(FileItem fileItem : list){
  8. if(!fileItem.isFormField()){ //如果是文件域
  9. //文件路径,替换掉特殊字符
  10. String filename =fileItem.getName().replace("\","/");
  11. //获取文件名
  12. filename =filename.substring(filename.lastIndexOf("/")+1);
  13. //获取文件类型
  14. String filetype =fileItem.getContentType();
  15. //获取文件大小
  16. Int filesize =fileItem.getSize();
  17. Connection conn = null;
  18. PrepareStatement preStmt = null;
  19. try{
  20. conn = DbManager.getConnection();
  21. preStmt = conn.prepareStatement(
  22. "insert into table_name (filename,filetype,size,content,date) values(?,?,?,?,?)");
  23. preStmt.setString(1,filename);
  24. preStmt.setString(2,filetype);
  25. preStmt.setInt(3,filesize);
  26. preStmt.setBinaryStream(4,fileItem.getInputStream(),filesize);
  27. preStmt.setTimestamp(5,newTimestamp(System.currentTimeMills()));
  28. preStmt.executeUpdate();
  29. }finally{
  30. if(preStmt != null) preStmt.close();
  31. if(conn != null) conn.close();
  32. }
  33. }
  34. }
  35. }
  36. %>
复制代码

读取二进制文件
  1. <%
  2. out.clear(); //清空一切输出
  3. int id=Integer.parseInt(request.getParameter("id")); //获取附件ID
  4. Connection conn= null;
  5. PrepareStatementpreStmt = null;
  6. ResultSet rs =null;
  7. try{
  8. conn =DbManager.getConnection();
  9. preStmt =conn.prepareStatement("select from table_name where id = ?");
  10. preStmt.setInt(1,id);
  11. rs =preStmt.executeQuery();
  12. if(rs.next()){
  13. response.reset(); //重置response
  14. response.setContentType(rs.getString("fileType"));//设置输出的文件类型
  15. response.setContentLength(ra.getInt("filesize"));//设置输出的文件长度
  16. InputStream ins = null;
  17. OutputStream ous = null;
  18. try{
  19. ins = rs.getBinaryStream("content");
  20. ous = response.getOutputStream();
  21. byte [] b = new byte[1024];
  22. int len = 0;
  23. while((len = ins.read(b)) !=-1){
  24. ous.write(b,0,len);
  25. }
  26. }finally{
  27. if(ous != null) ous.close();
  28. if(ins != null) ins.close();
  29. }
  30. }else{
  31. out.println("没有找到附件:"+id);
  32. }
  33. }finally{
  34. if(rs! = null) rs.close();
  35. if(preStmt != null) preStmt.close();
  36. if(conn != null) conn.close();
  37. }
  38. %>
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 03:32

Copyright 2015-2025 djqfx

返回顶部