It is common requirement in many projects to have file download facility.
File download facility can be achieved by many means, but in 11g + versions we have one very good component
to handle file download facility very quickly.
In 11g + versions we have one listener component called fileDownloadActionListener. Which can be triggered from any command related components like commandButton , commandLink etc.
It has three parameters filename, contentType, method.
filename : It is used to display the file name in response
method: The method will be present in managed bean. It is used to handle the file download related activities. Signature of this method is
public void (FacesContext context, OutputStream out) throws IOException
{
…… your code…
}
contentType: It is used to specify the content type.(like it is word document or pdf document etc.)
In the below example I have used fileDownloadActionListener with commandLink.
partialSubmit=”true”
binding=”#{fileDownloadBean.downloadLink}”>
method=”#{fileDownloadBean.download}” >
The method referred is
public void download(FacesContext context,
OutputStream out) throws IOException {
File f =
new File(this.directoryPath.getValue().toString() + “/” + downloadLink.getText());
FileInputStream fis;
byte[] b;
try {
fis = new FileInputStream(f);
int n;
while ((n = fis.available()) > 0) {
b = new byte[n];
int result = fis.read(b);
out.write(b, 0, b.length);
if (result == -1)
break;
}
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
}
So whatever file I want to download it will be downloaded using this listener. The coding type will be least one.
Please comment…