2015-10-16 18 views
1

我用這個命令存儲在SQL Server中的zip文件爲varbinary(最大值)到的OutputStream:獲取VARBINARY和發送XPages中

INSERT INTO Cache(name,zip) 
SELECT 'my_zip_file1',* FROM 
    OPENROWSET(BULK N'D:\folder\fol2\my_zip_file.zip', SINGLE_BLOB) AS import; 

併成功存儲的名稱和二進制數據名爲Cache的表。

在我xpage我有一個按鈕,發送到另一個下載頁面render=false和1行代碼beforeRenderResponse事件,以執行Java託管bean(即dl.download())。

我設法從託管的bean中使用jdbc,以便從關係數據庫(如db2和sql server)獲取和存儲數據。

在這種特殊情況下,我想知道如何從數據庫中獲取二進制數據?使用rs.getBytesrs.getBinaryStream

如何將它發送到http響應輸出? 下面我粘貼失敗代碼:

public void download(String filepath) { 
    Connection con; 
    PreparedStatement stm; 
    ResultSet rs; 
    byte[] buf = new byte[8192]; 
    //InputStream is = new ByteArrayInputStream(buf); 
    byte[] zip; 
    try { 
     Class.forName(jdbcClass); 
     con = DriverManager.getConnection(url); 
     String sql = "SELECT TOP 1 * FROM Cache where name = ?;"; 
     stm = con.prepareStatement(sql); 
     stm.setString(1, "D:\\folder\\fol2\\my_zip_file.zip"); 
     rs = stm.executeQuery(); 
     while (rs.next()) { 
      zip = rs.getBytes("zip"); 
      ByteArrayInputStream is = new ByteArrayInputStream(zip); 

      //System.out.println("AVAIL:"+zip.available()); 
      FacesContext facesContext = FacesContext.getCurrentInstance(); 
      ExternalContext externalContext = facesContext.getExternalContext(); 
      HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); 
      response.setContentType("application/zip, application/octet-stream"); 
      response.setHeader("Content-disposition", "attachment; filename=z.zip"); 
      response.setHeader("Cache-Control", "no-cache"); 
      ServletOutputStream sout = response.getOutputStream(); 

      int c = 0; 
      //while ((c = is.read()) > 0) { 
      while ((c = is.read(buf, 0, buf.length)) > 0) { 
       //sout.write(c); 
       sout.write(buf, 0, c); 
       //sout.flush(); 
      } 

     } 
    } 
} 

的錯誤是:

cant get writer while outputstream is used.

試圖代碼的另一個版本給我的錯誤:

output stream is closed

任何想法?

PS:我設法使它與一個文本文件一起工作。我從數據庫中獲取了一個字符串,並將包含此字符串的文件發送到輸出流。它是從瀏覽器下載的,一切正常。問題是與二進制文件作爲zip ...

回答

0

這是因爲你必須關閉響應。

facesContext.responseComplete();