I'm trying to download file from a JSF page, but when checking the content-length
in the browser I find it 0.
This is my method in the managed Bean :
public void downloadFile() throws IOException {
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
File file = new File("C:\\data\\contacts.doc");
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=contacts.doc");
response.setContentLength((int) file.length());
response.setContentType("application/octet-stream");
OutputStream out = response.getOutputStream();
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer =new byte[2048];
int offset = 0;
int byteRead =0;
while ((offset= input.read(buffer))!= -1 ) {
offset += byteRead ;
out.write(buffer,0,offset);
}
out.flush();
out.close();
input.close();
FacesContext.getCurrentInstance().getResponseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
this is the xhtml page :
<h:form>
<h:commandButton value="Download" action="#{helloBean.downloadFile}" />
</h:form>
I'm using Eclispe + Glassfish 4.