Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

How to download a file from the server using javaEE

The following snippet will accept a filename in the server's directory, set it as the content of the FacesContext for the user to download.

public String downloadXMLInvoice(String fileName) {
 File file = new File(getXmlInvoiceDir().getAbsolutePath() + File.separator + fileName);
 
 try {
  FacesContext context = FacesContext.getCurrentInstance();
  HttpServletResponse res = (HttpServletResponse) context.getExternalContext().getResponse();
  res.setContentType("application/force-download");
  res.setContentLength((int) file.length());
  res.addHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");

  OutputStream out = res.getOutputStream();
  InputStream fin = new FileInputStream(file);

  byte[] buf = new byte[1024];
  int sig = 0;
  while ((sig = fin.read(buf, 0, 1024)) != -1) {
   out.write(buf, 0, sig);
  }
  
  fin.close();
  out.flush();
  out.close();
  
  context.responseComplete();
 } catch (Exception e) {
  log.error(Epic failed :-) ", e.getMessage(), file.getAbsolutePath());
 }
 
 return null;
}
How to download a file from the server using javaEE How to download a file from the server using javaEE Reviewed by Edward Legaspi on Friday, October 23, 2015 Rating: 5

No comments:

Powered by Blogger.