我有一个使用PrimeFaces组件的Web应用程序。我试图从数据库下载一个文件,以保存到某人的客户端计算机。在代码中,我将字节数组写入下面显示的文件对象。但是,我不知道在触发该功能时如何触发下载对话栏。有人可以帮忙吗?
下载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>
答案 0 :(得分:1)
如果仔细查看showcase
你会看到你需要调用返回StreamedContent的函数。您可以将函数从void更改为StreamedContent,最后添加return file;