2015-05-30 69 views
2

我很抱歉我的英語。我用翻譯器。有一個Java代碼。從現場Posgresql BYTEA二進制數據,並將其存儲在一個文件數據庫中讀取:如何在xpages中將引用傳遞給Java中的文件

<code> 
    public static void saveToFile() throws IOException { 
    try { 
    Connection conn = JdbcUtil.getConnection(FacesContext.getCurrentInstance(), "derby1"); 
      ResultSet rs = conn.createStatement().executeQuery(
          "SELECT files FROM test_goverment where who='d'"); 
      byte[] imgBytes = null; 
      if (rs != null) { 
       while (rs.next()) { 
        imgBytes = rs.getBytes(1); 
       } 
       FileOutputStream os = new FileOutputStream("c:\\samoutput.txt"); 
       os.write(imgBytes); 
       os.flush(); 
       os.close(); 
      } 
      rs.close(); 
      conn.close(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     enter code here} 
    } 
</code> 

如何傳輸的文件下載到用戶的XPages。下載後刪除它。

回答

1

您只是想將查詢結果傳輸到瀏覽器客戶端進行下載並且不想保存它。

public static void downloadFile() throws IOException { 
    try { 
     FacesContext facesContext = FacesContext.getCurrentInstance(); 
     Connection conn = JdbcUtil.getConnection(facesContext, "derby1"); 
     ResultSet rs = conn.createStatement().executeQuery(
          "SELECT files FROM test_goverment where who='d'"); 
     byte[] imgBytes = null; 
     if (rs != null) { 
      while (rs.next()) { 
       imgBytes = rs.getBytes(1); 
      } 
      ExternalContext extCon = facesContext.getExternalContext(); 
      XspHttpServletResponse response = (XspHttpServletResponse)extCon.getResponse(); 
      response.reset(); 
      response.setContentType("text/plain"); 
      response.setHeader("Content-disposition", "attachment; filename=output.txt"); 
      response.setHeader("Cache-Control", "no-cache"); 
      OutputStream os = response.getOutputStream(); 
      os.write(imgBytes); 
      os.flush(); 
      facesContext.responseComplete(); 
      rs.close();    
     } 
     conn.close(); 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } 
} 

您還可以:

而是首先將查詢結果保存到文件並傳輸下載後
可以內容直接到XPage中的響應這樣的看看這個XSnippet。它向您展示瞭如何呈現文件以供下載,以防您想要/必須保留文件而不僅僅是流。

+0

非常感謝。有用.... – JohnLemon

相關問題