隨筆-8  評論-2  文章-24  trackbacks-0

          最近做一個 J2EE 項目,需要在 JSP 頁面實現對文件的上傳和下載。很早以前就知道 JDBC 支持大對象( LOB )的存取,以為很容易,做起來才發現問題多多,讀了一大堆文章,反而沒有什么頭緒了。正如一位網友文章所講:“…網絡上的教程 99% 都是行不通的,連 SUN 自己的文檔都一直錯誤……”,實際情況大致如此了。

          ?

          存取 BLOB 出現這么多問題,我認為大半是由數據庫開發商、應用服務器商在 JDBC 驅動上的不兼容性帶來的。而實際應用中,每個人的開發運行環境不同,使得某個網友的 solution 沒有辦法在別人的應用中重現,以至于罵聲一片。至于為什么會不兼容、有哪些問題,我沒有時間去弄清,這里只說說我們怎樣解決了問題的。

          ?

          基于上述原因,先列出我們的開發環境,免得有人配不出來,招人唾罵。

          數據庫 Oracle 9i

          應用服務器 BEA Weblogic 8.11

          開發工具 JBuilder X

          ?

          JSP 實現文件 Upload/Download 可以分成這樣幾塊 :文件提交到形成 InputSteam InputSteam BLOB 格式入庫;數據從庫中讀出為 InputSteam InputStream 輸出到頁面形成下載文件。先說 BLOB 吧。

          ?

          1.? BLOB 入庫

          (1)?????? 直接獲得數據庫連接的情況

          這是 Oracle 提供的標準方式,先插入一個空 BLOB 對象,然后 Update 這個空對象。代碼如下:

          // 得到數據庫連接(驅動包是 weblogic 的,沒有下載任何新版本)

          Class.forName("oracle.jdbc.driver.OracleDriver");

          Connection con = DriverManager.getConnection(

          ????????? "jdbc:oracle:thin:@localhost:1521:testdb", "test", "test");

          // 處理事務

          con.setAutoCommit(false);

          Statement st = con.createStatement();

          // 插入一個空對象

          st.executeUpdate("insert into BLOBIMG? values(103,empty_blob())");

          // for update 方式鎖定數據行

          ResultSet rs = st.executeQuery(

          ????????? "select contents from? BLOBIMG? where? id=103 for update");

          if (rs.next()) {

          ?? // 得到 java.sql.Blob 對象,然后 Cast oracle.sql.BLOB

          oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1).;

          ?? // 到數據庫的輸出流

          OutputStream outStream = blob.getBinaryOutputStream();

          ?? // 這里用一個文件模擬輸入流

          File file = new File("d:\\proxy.txt");

          ? InputStream fin = new FileInputStream(file);

          // 將輸入流寫到輸出流

          byte[] b = new byte[blob.getBufferSize()];

          ??????? int len = 0;

          ??????? while ( (len = fin.read(b)) != -1) {

          ????????? outStream.write(b, 0, len);

          ????????? //blob.putBytes(1,b);

          ??????? }

          ?

          ?? // 依次關閉(注意順序)

          fin.close();

          ?? outStream.flush();

          ?? outStream.close();

          ?? con.commit();

          ?? con.close();

          ?

          (2)?????? 通過 JNDI 獲得數據庫連接

          Weblogic 中配置到 Oracle JDBC Connection Pool DataSource ,綁定到 Context 中,假定綁定名為 ”orads”

          為了得到數據庫連接,做一個連接工廠,主要代碼如下:

          Context context = new InitialContext();

          ds = (DataSource) context.lookup("orads");

          return ds.getConnection();

          以下是 BLOB 寫入數據庫的代碼:

          ?

          Connection con = ConnectionFactory.getConnection();

          con.setAutoCommit(false);

          Statement st = con.createStatement();

          st.executeUpdate("insert into BLOBIMG values(103,empty_blob())");

          ResultSet rs = st.executeQuery(

          ????????? "select contents from? BLOBIMG? where? id=103 for update");

          if (rs.next()) {

          ?? ?// 上面代碼不變

          // 這里不能用 oracle.sql.BLOB ,會報 ClassCast 異常

          weblogic.jdbc.vendor.oracle.OracleThinBlobblob = (weblogic.jdbc.vendor.oracle.OracleThinBlob) rs.getBlob(1);

          ??? // 以后代碼也不變

          OutputStream outStream = blob.getBinaryOutputStream();

          File file = new File("d:\\proxy.txt");

          ? InputStream fin = new FileInputStream(file);

          byte[] b = new byte[blob.getBufferSize()];

          ??????? int len = 0;

          ??????? while ( (len = fin.read(b)) != -1) {

          ????????? outStream.write(b, 0, len);

          ??????? }

          ?

          fin.close();

          ?? outStream.flush();

          ?? outStream.close();

          ?? con.commit();

          ?? con.close();

          ?

          2.? BLOB 出庫

          從數據庫中讀出 BLOB 數據沒有上述由于連接池的不同帶來的差異,只需要 J2SE 的標準類 java.sql.Blob 就可以取得輸出流(注意區別 java.sql.Blob oracle.sql.BLOB )。代碼如下:

          Connection con = ConnectionFactory.getConnection();

          con.setAutoCommit(false);

          Statement st = con.createStatement();

          // 這里的 SQL 語句不再需要 ”for update”

          ResultSet rs = st.executeQuery(

          ????????? "select contents from? BLOBIMG? where? id=103 ");

          if (rs.next()) {

          ?? java.sql.Blob blob = rs.getBlob(1);

          ?

          ?? InputStream ins = blob.getBinaryStream();

          ?

          ??? // 用文件模擬輸出流

          File file = new File("d:\\output.txt");

          ?? OutputStream fout = new FileOutputStream(file);

          ?

          ??? // 下面將 BLOB 數據寫入文件

          ??? byte[] b = new byte[1024];

          ??? int len = 0;

          ??????? while ( (len = ins.read(b)) != -1) {

          ????????? fout.write(b, 0, len);

          ??????? }

          ? // 依次關閉

          ? fout.close();

          ? ins.close();

          ? con.commit();

          ? con.close();

          ?

          3.? JSP 頁面提交文件到數據庫

          ?

          (1)?????? 提交頁面的代碼如下:

          <form action="handle.jsp" enctype="multipart/form-data" method="post" >

          <input type="hidden" name="id" value="103"/>

          <input type="file"? name="fileToUpload">

          <input type="submit"? value="Upload">

          </form>

          ?

          (2)?????? 由于 JSP 沒有提供文件上傳的處理能力,只有使用第三方的開發包。網絡上開源的包有很多,我們這里選擇 Apache Jakarta FileUpload ,在 http://jakarta.apache.org/commons/fileupload/index.html 可以得到下載包和完整的 API 文檔。法奧為 adajspException

          處理頁面( handle.jsp )的代碼如下

          <%

          boolean isMultipart = FileUpload.isMultipartContent(request);

          ??? if (isMultipart) {

          ????? // 建立一個新的 Upload 對象

          ????? DiskFileUpload upload = new DiskFileUpload();

          ?

          ??? // 設置上載文件的參數

          ??? //upload.setSizeThreshold(yourMaxMemorySize);

          ??? //upload.setSizeMax(yourMaxRequestSize);

          ??? String rootPath = getServletConfig().getServletContext().getRealPath("/") ;

          ??? upload.setRepositoryPath(rootPath+"\\uploads");

          ?

          ???? // 分析 request 中的傳來的文件流,返回 Item 的集合,

          ???? // 輪詢 Items ,如果不是表單域,就是一個文件對象。

          ????? List items = upload.parseRequest(request);

          ????? Iterator iter = items.iterator();

          ????? while (iter.hasNext()) {

          ??????? FileItem item = (FileItem) iter.next();

          ??????? // 如果是文件對象

          if (!item.isFormField()) {

          ?

          ????????? // 如果是文本文件,可以直接顯示

          ????????? //out.println(item.getString());

          ?

          ????????? // 將上載的文件寫到服務器的 \WEB-INF\webstart\ 下,文件名為 test.txt

          ????????? //File uploadedFile = new File(rootPath+"\\uploads\\test.txt");

          ????????? //item.write(uploadedFile);

          ?

          ????? ??// 下面的代碼是將文件入庫(略):

          ??????? // 注意輸入流的獲取

          InputStream uploadedStream = item.getInputStream();

          ??????? }

          ??????? // 否則是普通表單

          else{

          ????????? out.println("FieldName: " + item.getFieldName()+"<br>");

          ????????? out.println("Value: "+item.getString()+"<br>");??????? }

          ????? }

          ??? }

          %>

          ?

          4.? 從數據庫讀取 BLOB 然后保存到客戶端磁盤上

          這段代碼有點詭異,執行后將會彈出文件保存對話窗口,將 BLOB 數據讀出保存到本地文件。全文列出如下:

          <%@ page contentType="text/html; charset=GBK" import="java.io.*" import="java.sql.*" import="test.global.ConnectionFactory"%><%

          ????? Connection con = ConnectionFactory.getConnection();

          ????? con.setAutoCommit(false);

          ????? Statement st = con.createStatement();

          ?

          ???? ?ResultSet rs = st.executeQuery(

          ???????????????????? "select contents from? BLOBIMG? where? id=103 ");

          ????? if (rs.next()) {

          ??????? Blob blob = rs.getBlob(1);

          ??????? InputStream ins = blob.getBinaryStream();

          ?

          ??????? response.setContentType("application/unknown");

          ??????? response.addHeader("Content-Disposition", "attachment; filename="+"output.txt");

          ?

          ??????? OutputStream outStream = response.getOutputStream();

          ??????? byte[] bytes = new byte[1024];

          ??????? int len = 0;

          ??????? while ((len=ins.read(bytes))!=-1) {

          ??????????? outStream.write(bytes,0,len);

          ??????? }

          ??????? ins.close();

          ??????? outStream.close();

          ??????? outStream = null;

          ??????? con.commit();

          ??????? con.close();

          ????? }

          %>

          注意,在 <% … … %> 之外,絕對不能有任何字符,空格或回車都不行 ,不然會導致 outputStream 出錯,對非 ASCII 輸出文件來說就是格式錯誤不可讀。

          ?

          5.? 最后一個問題就是把以 BLOB 形式存放的圖像文件直接顯示到 JSP 頁面上

          解決辦法是:首先將圖像文件從數據庫中讀出形成 InputStream ,然后用 Servlet 寫到頁面輸出流上。最后,將這個 servlet 包含到 JSP 頁面適當的圖像位置上。

          ?

          Servlet 代碼如下:

          public void doGet(HttpServletRequest request, HttpServletResponse response) throws

          ????? ServletException, IOException {

          ??? int id = Integer.parseInt(request.getParameter("id"));

          ?

          ??? try {

          ????? Connection con = ConnectionFactory.getConnection();

          ????? con.setAutoCommit(false);

          ????? String sql = "select contents from? BLOBIMG? where? id= ? ";

          ????? PreparedStatement psmt = con.prepareStatement(sql);

          ????? psmt.setInt(1, id);

          ????? ResultSet rs = psmt.executeQuery();

          ????? if (rs.next()) {

          ??????? Blob bb = rs.getBlob(1);

          ??????? InputStream ins = bb.getBinaryStream();

          ?

          ? ?????? response.setContentType("image/gif");

          ??????? OutputStream outStream = response.getOutputStream();

          ??????? byte[] bytes = new byte[1024];

          ??????? int len = 0;

          ??????? while ( (len = ins.read(bytes)) != -1) {

          ????????? outStream.write(bytes, 0, len);

          ??????? }

          ??????? ins.close();

          ??????? outStream.close();

          ??????? outStream = null;

          ??????? con.commit();

          ??????? con.close();

          ????? }

          ??? }

          ??? catch (Exception ex) {}

          ? }

          ?

          JSP 代碼如下:

          <img src="showimgae?id=110">

          注意在 web.xml 中配置好 Servlet Mapping

          ?

          這樣, BLOB JSP 中的基本應用就完整了。

          ?

          本文參考了大量網友文章,特此表示感謝。

          1.??????? 通過 JDBC 操縱 Oracle 數據庫 LOB 字段的幾種情況分析 http://dev.csdn.net/develop/article/26/26786.shtm

          2.??????? 關于將文件用 java.sql.Blob 類型的 blob 操作寫入 oracle 數據庫中的 blob http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=197116

          3.??????? weblogic7 可以操作 Oracle9i 的大字段 ,Weblogic8 為什么不可以 ? http://dev2dev.bea.com.cn/bbs/thread.jspa?forumID=123&threadID=5390&messageID=23598

          4.??????? How to show file download dialog box in IE 6.0 http://www.experts-exchange.com/Web/Web_Languages/JSP/Q_20842012.html

          5.??????? SQL SERVER 2000 中的 JPEG 圖片在 Jsp 上顯示亂碼問題 http://search.csdn.net/Expert/topic/2462/2462925.xml?temp=3.071231E-02



          環境:
          Database: Oracle 9i
          App Server: BEA Weblogic 8.14
          表結構:
          CREATE TABLE TESTBLOB (ID Int, NAME Varchar2(20), BLOBATTR Blob)
          CREATE TABLE TESTBLOB (ID Int, NAME Varchar2(20), CLOBATTR Clob)
          ?
          JAVA可以通過JDBC,也可以通過JNDI訪問并操作數據庫,這兩種方式的具體操作存在著一些差異,由于通過App Server的數據庫連接池JNDI獲得的數據庫連接提供的java.sql.Blob和java.sql.Clob實現類與JDBC方式提供的不同,因此在入庫操作的時候需要分別對待;出庫操作沒有這種差異,因此不用單獨對待。

          一、BLOB操作
          1、入庫
          (1)JDBC方式
          ??? //通過JDBC獲得數據庫連接
          ??? Class.forName("oracle.jdbc.driver.OracleDriver");
          ??? Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:testdb", "test", "test");
          ??? con.setAutoCommit(false);
          ??? Statement st = con.createStatement();
          ??? //插入一個空對象empty_blob()
          ??? st.executeUpdate("insert into TESTBLOB (ID, NAME, BLOBATTR) values (1, "thename", empty_blob())");
          ??? //鎖定數據行進行更新,注意“for update”語句
          ??? ResultSet rs = st.executeQuery("select BLOBATTR from TESTBLOB where ID=1 for update");
          ??? if (rs.next())
          ??? {
          ??????? //得到java.sql.Blob對象后強制轉換為oracle.sql.BLOB
          ??????? oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("BLOBATTR");
          ??????? OutputStream outStream = blob.getBinaryOutputStream();
          ??????? //data是傳入的byte數組,定義:byte[] data
          ??????? outStream.write(data, 0, data.length);
          ??? }
          ??? outStream.flush();
          ??? outStream.close();
          ??? con.commit();
          ??? con.close();
          (2)JNDI方式
          ??? //通過JNDI獲得數據庫連接
          ??? Context context = new InitialContext();
          ??? ds = (DataSource) context.lookup("ORA_JNDI");
          ??? Connection con = ds.getConnection();
          ??? con.setAutoCommit(false);
          ??? Statement st = con.createStatement();
          ??? //插入一個空對象empty_blob()
          ??? st.executeUpdate("insert into TESTBLOB (ID, NAME, BLOBATTR) values (1, "thename", empty_blob())");
          ??? //鎖定數據行進行更新,注意“for update”語句
          ??? ResultSet rs = st.executeQuery("select BLOBATTR from TESTBLOB where ID=1 for update");
          ??? if (rs.next())
          ??? {
          ??????? //得到java.sql.Blob對象后強制轉換為weblogic.jdbc.vendor.oracle.OracleThinBlob(不同的App Server對應的可能會不同)
          ??????? weblogic.jdbc.vendor.oracle.OracleThinBlob blob = (weblogic.jdbc.vendor.oracle.OracleThinBlob) rs.getBlob("BLOBATTR");
          ??????? OutputStream outStream = blob.getBinaryOutputStream();
          ??????? //data是傳入的byte數組,定義:byte[] data
          ??????? outStream.write(data, 0, data.length);
          ??? }
          ??? outStream.flush();
          ??? outStream.close();
          ??? con.commit();
          ??? con.close();
          2、出庫
          ??? //獲得數據庫連接
          ??? Connection con = ConnectionFactory.getConnection();
          ??? con.setAutoCommit(false);
          ??? Statement st = con.createStatement();
          ??? //不需要“for update”
          ??? ResultSet rs = st.executeQuery("select BLOBATTR from TESTBLOB where ID=1");
          ??? if (rs.next())
          ??? {
          ??????? java.sql.Blob blob = rs.getBlob("BLOBATTR");
          ??????? InputStream inStream = blob.getBinaryStream();
          ??????? //data是讀出并需要返回的數據,類型是byte[]
          ??????? data = new byte[input.available()];
          ??????? inStream.read(data);
          ??????? inStream.close();
          ??? }
          ??? inStream.close();
          ??? con.commit();
          ??? con.close();
          ?
          二、CLOB操作
          1、入庫
          (1)JDBC方式
          ??? //通過JDBC獲得數據庫連接
          ??? Class.forName("oracle.jdbc.driver.OracleDriver");
          ??? Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:testdb", "test", "test");
          ??? con.setAutoCommit(false);
          ??? Statement st = con.createStatement();
          ??? //插入一個空對象empty_clob()
          ??? st.executeUpdate("insert into TESTCLOB (ID, NAME, CLOBATTR) values (1, "thename", empty_clob())");
          ??? //鎖定數據行進行更新,注意“for update”語句
          ??? ResultSet rs = st.executeQuery("select CLOBATTR from TESTCLOB where ID=1 for update");
          ??? if (rs.next())
          ??? {
          ??????? //得到java.sql.Clob對象后強制轉換為oracle.sql.CLOB
          ??????? oracle.sql.CLOB clob = (oracle.sql.CLOB) rs.getClob("CLOBATTR");
          ??????? Writer outStream = clob.getCharacterOutputStream();
          ??????? //data是傳入的字符串,定義:String data
          ??????? char[] c = data.toCharArray();
          ??????? outStream.write(c, 0, c.length);
          ??? }
          ??? outStream.flush();
          ??? outStream.close();
          ??? con.commit();
          ??? con.close();
          (2)JNDI方式
          ??? //通過JNDI獲得數據庫連接
          ??? Context context = new InitialContext();
          ??? ds = (DataSource) context.lookup("ORA_JNDI");
          ??? Connection con = ds.getConnection();
          ??? con.setAutoCommit(false);
          ??? Statement st = con.createStatement();
          ??? //插入一個空對象empty_clob()
          ??? st.executeUpdate("insert into TESTCLOB (ID, NAME, CLOBATTR) values (1, "thename", empty_clob())");
          ??? //鎖定數據行進行更新,注意“for update”語句
          ??? ResultSet rs = st.executeQuery("select CLOBATTR from TESTCLOB where ID=1 for update");
          ??? if (rs.next())
          ??? {
          ??????? //得到java.sql.Clob對象后強制轉換為weblogic.jdbc.vendor.oracle.OracleThinClob(不同的App Server對應的可能會不同)
          ??????? weblogic.jdbc.vendor.oracle.OracleThinClob clob = (weblogic.jdbc.vendor.oracle.OracleThinClob) rs.getClob("CLOBATTR");
          ??????? Writer outStream = clob.getCharacterOutputStream();
          ??????? //data是傳入的字符串,定義:String data
          ??????? char[] c = data.toCharArray();
          ??????? outStream.write(c, 0, c.length);
          ??? }
          ??? outStream.flush();
          ??? outStream.close();
          ??? con.commit();
          ??? con.close();
          2、出庫
          ??? //獲得數據庫連接
          ??? Connection con = ConnectionFactory.getConnection();
          ??? con.setAutoCommit(false);
          ??? Statement st = con.createStatement();
          ??? //不需要“for update”
          ??? ResultSet rs = st.executeQuery("select CLOBATTR from TESTCLOB where ID=1");
          ??? if (rs.next())
          ??? {
          ??????? java.sql.Clob clob = rs.getClob("CLOBATTR");
          ??????? Reader inStream = clob.getCharacterStream();
          ??????? char[] c = new char[(int) clob.length()];
          ??????? inStream.read(c);
          ??????? //data是讀出并需要返回的數據,類型是String
          ??????? data = new String(c);
          ??????? inStream.close();
          ??? }
          ??? inStream.close();
          ??? con.commit();
          ??? con.close();
          ?
          需要注意的地方:
          1、java.sql.Blob、oracle.sql.BLOB、weblogic.jdbc.vendor.oracle.OracleThinBlob幾種類型的區別
          2、java.sql.Clob、oracle.sql.CLOB、weblogic.jdbc.vendor.oracle.OracleThinClob幾種類型的區別
          posted on 2006-12-19 13:39 MyBox 閱讀(1934) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 阳城县| 新晃| 洛隆县| 延吉市| 西平县| 无锡市| 新兴县| 永济市| 樟树市| 临潭县| 河西区| 茂名市| 吉木乃县| 梧州市| 绿春县| 石阡县| 垫江县| 黎川县| 呈贡县| 平定县| 凤阳县| 延吉市| 香港 | 五峰| 蓝山县| 蒙自县| 峡江县| 洛宁县| 崇礼县| 年辖:市辖区| 滦南县| 武胜县| 苏尼特左旗| 依兰县| 马尔康县| 乌拉特后旗| 电白县| 宣威市| 东乡| 白城市| 贵溪市|