JSP Oracle BLOB 图片保存

来源:互联网 发布:网络安全技术有哪些 编辑:程序博客网 时间:2024/06/05 05:32
  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.         /* 取出此BLOB对象 */
  42.         blob = (oracle.sql.BLOB)rs.getBlob("imag");
  43.         /* 向BLOB对象中写入数据 */
  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>