天天看點

JSP Oracle BLOB 圖檔儲存

  1. <%@?page?contentType="text/html;image/jpg;charset=gb2312"?language="java"?import="java.sql.*"?errorPage=""?%>
  2. <html>
  3. <head>
  4. <meta?http-equiv="Content-Type"?content="text/html;?charset=gb2312">
  5. <title>瀵煎?ュ?劇??</title>
  6. </head>
  7. <body>
  8. <h2>瀵煎?ュ?劇??锛?</h2>
  9. <%@?page?import="java.io.*"%>?
  10. <%@?page?import="oracle.sql.BLOB"%>?
  11. <%
  12. try
  13. {
  14. ????Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
  15. ????int?imgId=1;
  16. ??????
  17. ????Statement?st?=?null;
  18. ????
  19. ????BLOB?blob?=?null;?//?劇??绫誨??
  20. ????OutputStream?outputStream?=?null;?//杈??烘?
  21. ????File?file?=?null;?//??浠?
  22. ????FileInputStream?inputStream?=null;
  23. ????file?=?new?File("i://tomcat.gif");?//??浠?
  24. ????inputStream?=?new?FileInputStream(file);?//杈??ユ?
  25. ????ResultSet?rs?=?null;
  26. ????
  27. ????String?url="jdbc:oracle:thin:@localhost:1521:ORCL";
  28. ????Connection?conn?=DriverManager.getConnection(url,"system","oracle");
  29. ????conn.setAutoCommit(false);?//浜??╃?辯?搴?????浣?
  30. ????st?=?conn.createStatement();
  31. ????rs?=?st.executeQuery("select?nvl(max(id),0)?as?maxid?from?hr.psn");
  32. ????if?(rs.next())
  33. ????{
  34. ????????imgId+=rs.getInt("maxid");
  35. ????}
  36. ????rs.close();
  37. ????st.executeQuery("insert?into?hr.psn?values("+?imgId?+",'"+file.length()+"',empty_blob())");
  38. ????rs?=?st.executeQuery("select?imag?from?hr.psn?where?id="+?imgId?+"?for?update");
  39. ????if?(rs.next())?
  40. ????{
  41. ????????
  42. ????????blob?=?(oracle.sql.BLOB)rs.getBlob("imag");
  43. ????????
  44. ????????OutputStream?outt?=?blob.getBinaryOutputStream();
  45. ????????BufferedInputStream?in?=?new?BufferedInputStream(new?FileInputStream(file));
  46. ????????int?c;
  47. ????????while?((c=in.read())!=-1)
  48. ????????{
  49. ???????????outt.write(c);
  50. ????????}
  51. ????????in.close();
  52. ????????outt.close();
  53. ????}
  54. ????
  55. ????conn.commit();??????????????
  56. ????
  57. ????rs.close();
  58. ????st.close();
  59. ????conn.close();
  60. }
  61. catch?(Exception?e)
  62. {
  63. ????e.printStackTrace();
  64. }
  65. %>
  66. </body>
  67. </html>