I am sorry for my English. I use a translator. There is a code to Java. Reads from the database of the field Posgresql bytea binary data and stores it in a file:
<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>
How to transfer the file to download to user in Xpages. And remove it after downloading.
You just want to transfer the query result to browser client for download and don't want to save it.
Instead of saving the query result to a file first and transfer it for download later
you can stream the content direct to XPage's response like this:
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();
}
}
You might also have a look at this XSnippet. It shows you how to present files for download in case you want/have to stay with files instead just streams.