Monday, April 30, 2007

forcing file save dialog in web browser

Sometimes we want to download a file from the web browser in stead of opening the contents of the file. If the file is a text or xml file then the default operation for the browser is to open it. Then we have to save the file by File->Save As. But what will happen if you want to invoke the save dialog box of the browser if you click the link. then you have to manually force the response header to tell the browser that this is not a known MIME type. you can set
content-type="application/octet-stream"

most of the browser will invoke the default save dialog. but the MSIE will not. halai poora foul. To invoke it from IE you have to add another varialble to the response header.
content-disposition="attachment"

these codes can be added from html. but most of the times the file is generated in the server end. so here is the java code which reads a
file from the server and passes the file contents to the client through the response header.


FacesContext fc = FacesContext.getNewInstance();
HttpServletResponse response = (
HttpServletResponse) fc.getExternalContext().getResponse();
OutputStream out = null;
InputStream in = null;

response.setContentType("application/x-mydownload");
response.setHeader("content-disposition=", "attachment;filename=\"myFile.txt\"");

try {
out = response.getOutputStream();
in = new FileInputStream(new File("inputfile.txt");
int i = 0;
while((i=in.read()) != -1) {
out.write((byte)i);
}
out.flush();
out.close();
fc.responseComplete(); //this is important

} catch (IOException e) {
System.out.println("exception occured: "+ e.getMessage());
} finally {
try{
if(in != null) {
in.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}




No comments: