I have read a lot of articles and none have solved the problem for me.
First of all, I'm making use of RichFaces fileUpload component, wich is working fine when it comes to upload the file. But when I'm trying to retrieve the file in order to download it (e.g. it is retrieved from database as a byte array), the page is reloaded with a bunch of strange characters.
Here is my download function:
public void downloadFile() {
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=file.pdf");
try {
ServletOutputStream os = response.getOutputStream();
os.write(uploadItem.getData()); // uploadItem.getData() returns a byte array
os.flush();
os.close();
FacesContext.getCurrentInstance().responseComplete();
} catch(Exception e) {
LOG.error("\nFailure : " + e.toString() + "\n");
}
}
When this function is invoked, the page is reloaded with a bunch of strange characters. I'm wondering why the "Save as" windows is not being called so I could effectively save the file.
Example showing the strange characters
It is important to mention that when creating a new file localy through the code below it worked perfectly.
byte data[] = uploadItem.getData();
File file = new File("D:/out.pdf");
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.close();
Thanks in advance!
SOLVED
As pointed by @BalusC (thanx!) this article contains the straight information needed to solve the issue.
This suggests that the request is an ajax request. You can't download files by >ajax. Ajax requests are processed by JavaScript which has for obvious security >reasons no facilities to programmatically pop a Save As dialogue nor to >access/manipulate client's disk file system.