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 downlo...
https://www.czetsuyatech.com/2015/10/javaee-download-a-file.html
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; }
Post a Comment