Reputation: 89
I have a web application that uses PrimeFaces components. I am trying to download a file from the database to be saved to someones client computer. In the code, I am writing the byte array to the file object shown below. However, I do not know how to trigger the download dialog bar when the function is triggered. Can someone please help?
Download function in 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>
Upvotes: 0
Views: 3177
Reputation: 149
If you look carefully at showcase
you will see that you need to call function that returns StreamedContent. You could changed your function from void to StreamedContent and at the end add return file;
Upvotes: 1