如何在xpages中从Java传递对文件的引用

时间:2015-05-30 13:35:29

标签: java xpages xpages-ssjs xpages-extlib ssjs

我很抱歉我的英语。我用翻译器。 Java有一个代码。从Posgresql bytea二进制数据字段的数据库中读取并将其存储在文件中:

<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 个答案:

答案 0 :(得分:1)

您只想将查询结果传输到浏览器客户端进行下载,并且不想保存。

而不是先将查询结果保存到文件中,然后将其传输下载 您可以流式内容直接到XPage的响应,如下所示:

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();
    }
}

您可能还会看一下这个XSnippet。它向您展示了如何在需要/必须保留文件而不仅仅是流的情况下呈现要下载的文件。