You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@myfaces.apache.org by Apache Wiki <wi...@apache.org> on 2006/06/13 05:31:58 UTC
[Myfaces Wiki] Update of "Sending Files (like PDF) to the Browser" by
ozwolverine
Dear Wiki user,
You have subscribed to a wiki page or wiki category on "Myfaces Wiki" for change notification.
The following page has been changed by ozwolverine:
http://wiki.apache.org/myfaces/Sending_Files_%28like_PDF%29_to_the_Browser
New page:
= Sending Files (like PDF) to the Browser How To =
== Introduction ==
When you need the user to be able to download a file that is stored somewhere in the server.
So the idea is to send the file to the Response, then the user will be presented with a
Open/save dialog for him/her to take the required action.
== How to do it ==
You have to bind an action in the JSP to a method in your backing bean
The content of the method could be like this
'''//We must get first our context'''
FacesContext context = FacesContext.getCurrentInstance();
'''//Then we have to get the Response where to put write our file'''
HttpServletResponse response =
( HttpServletResponse ) context.getExternalContext().getResponse();
'''//Now we create some variable we will use for writting the file to the response'''
String filePath = null;
int read = 0;
byte[] bytes = new byte[1024];
'''//Be sure to retrieve the absolute path to the file with the required method'''
filePath = pathToTheFile;
'''//Now set the content type for our response, be sure to user the correct'''
'''//this content type is ok for, lets say some kind of text file (like a csv)'''
response.setContentType("application/pdf");
'''//This is another important attribute for the header of the response'''
'''//Here fileName, is a String with the name that you will suggest as a name to save as'''
'''//I use the same name as it is stored in the file system of the server.'''
response.setHeader("Content-Disposition", "attachment;filename=\"" +
fileName + "\"");
'''//Streams to use'''
FileInputStream fis = null;
OutputStream os = null;
'''//First we load the file in our InputStream '''
fis = new FileInputStream(new File(filePath ));
os = response.getOutputStream();
'''//While there are still bytes in the file, read them and write them to our OutputStream'''
while((read = fis.read(bytes)) != -1){
os.write(bytes,0,read);
}
'''//Clean resources'''
os.flush();
os.close();
'''//This option isn't quite necessary, It worked for me with or without it'''
FacesContext.getCurrentInstance().responseComplete();
'''//End of the method '''