Monday, March 11, 2013

Primefaces fileDownload in Liferay

When I tried to use <p:fileDownload /> in Liferay, with the simplest code shown in the demo site.
primefaces fileDownload code snippet
But the file is failed to download.
To resolve this issue, I ended up with the following steps.
Notes: issue reported in Liferay - http://issues.liferay.com/browse/FACES-1513

Public StreamData getFile() {
  // 1. initialize the fileInputStream
  // 2. get Liferay's ServletResponse
  // 3. write the file into the outputStream
  // 4. return null to this method
}


Sample codes:

public StreamedContent getFile() throws Exception {

 // 1. initialize the fileInputStream
 File localfile = new File("C:/kian.png");
 FileInputStream fis = new FileInputStream(localfile);

 // 2. get Liferay's ServletResponse
 PortletResponse portletResponse = (PortletResponse) FacesContext
   .getCurrentInstance().getExternalContext().getResponse();
 HttpServletResponse res = PortalUtil
   .getHttpServletResponse(portletResponse);
 res.setHeader("Content-Disposition", "attachment; filename=\""
   + "downloaded-kian.png" + "\"");//
 res.setHeader("Content-Transfer-Encoding", "binary");
 res.setContentType("application/octet-stream");
 res.flushBuffer();

 // 3. write the file into the outputStream
 OutputStream out = res.getOutputStream();
 byte[] buffer = new byte[4096];
 int bytesRead;
 while ((bytesRead = fis.read(buffer)) != -1) {
  out.write(buffer, 0, bytesRead);
  buffer = new byte[4096];
 }

 // 4. return null to this method
 return null;
}


Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...