使用PrimeFaces下载图像文件



我有一个使用PrimeFaces组件的web应用程序。我正试图从数据库中下载一个文件保存到某人的客户端计算机。在代码中,我将字节数组写入如下所示的文件对象。但是,我不知道如何触发下载对话框时,该功能被触发。有人能帮帮我吗?

Download bean

中的下载功能
public void fileDownload(int id) throws IOException {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        DBConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demeter2.0", "root", "root");
    } catch (SQLException | ClassNotFoundException ex) {
        Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
    }
    PreparedStatement pst = null;
    try {
        if (DBConn != null) {
            String sql = "Select * FROM graph WHERE id='" + id + "'";
            pst = (PreparedStatement) DBConn.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            if (!rs.next()) {
            } else {
                rs.beforeFirst();
                while (rs.next()) {
                    // File file = new File("c:/newfile.png");
                    Blob b = rs.getBlob(2);
                    byte barr[] = new byte[(int) b.length()];
                    barr = b.getBytes(1, (int) b.length());
                    InputStream is = new ByteArrayInputStream(barr);
                    System.out.print("hello");
                    file = new DefaultStreamedContent(is, "image/png", "chart.png");
                    System.out.print(file);
                }//end while
            }
        }
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        try {
            pst.close();
            DBConn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

download.xhtml

<h:form>
    <p:dataTable var="download" value="#{download.allGraph()}">
        <p:column headerText="Id">
            <h:outputText value="#{download.id}" />
        </p:column>
        <p:column headerText="Date Added">
            <h:outputText value="#{download.date}" />
        </p:column>
        <p:column headerText="Download">
            <p:commandLink id="downloadLink" value="Download" ajax="false">
                <p:fileDownload value="#{download.fileDownload(download.id)}" />
            </p:commandLink>
        </p:column>
    </p:dataTable>
</h:form>

如果你仔细看橱窗您将看到需要调用返回StreamedContent的函数。您可以将函数从void更改为StreamedContent,并在最后添加return file;

相关内容

  • 没有找到相关文章

最新更新