2

我为我的英语感到抱歉。我用翻译器。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 中将要下载的文件传输给用户。并在下载后将其删除。

4

1 回答 1

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。它向您展示了如何呈现文件以供下载,以防您想要/必须保留文件而不是流。

于 2015-05-30T14:28:23.877 回答