Sunday, July 25, 2010

Downloading file the right way

Often I had faced this problem while providing a file download functionality that
instead of providing a prompt the file gets opened in the browser itself.
This is because for known MIME (Multipurpose Internet Mail Extensions) types such as Microsoft Word ("application/ms-word") or images(application/gif, application/jpeg), the default behavior is to open the document in browser itself. Specially in cases of text or csv files such behaviour is observed.

So the objective is you serve a document from a Web server, and it immediately prompts to save that document directly to the user's disk, without opening it in the browser.

It is a matter of setting the right content-disposition and file-options. Below code should be a help to anybody facing such a problem


ServletOutputStream sos = null;
// this can be a path of your repository or a relative path
String uploadedFilePath = "C:/";

String fileName = request.getParameter("filename");
File file = new File( uploadedFilePath + "/" + fileName );
FileInputStream fis = new FileInputStream(file);
int size= (int) file.length();

// determine the mime-type for safe downloading
String ext = fileName.substring(fileName.indexOf("."), fileName.length());
ext = ext.toLowerCase();

if(ext.endsWith(".jpg") || ext.endsWith(".jpeg"))
{
response.setContentType("image/jpeg");
}
else if(ext.endsWith(".gif"))
{
response.setContentType("image/gif");
}
else if(ext.endsWith(".pdf"))
{
response.setContentType("application/pdf");
}
else if(ext.endsWith(".csv"))
{
response.setContentType("application/csv");
}
else
{
response.setContentType("application/octet-stream");
}

response.setHeader("Content-disposition:","attachment; filename=" + fileName );
response.setHeader("cache-control", "no-cache");

byte[] tmpBuffer=null;
sos = response.getOutputStream();
if ( size > 0)
{
tmpBuffer = new byte[size];
fis.read(tmpBuffer);
sos.write(tmpBuffer);
fis.close();
}
sos.flush();
sos.close();


Do check-out this post on a related exception

Happy Coding !!

1 comment:

  1. a list of some commonly used mime-types can be found here
    http://www.webmaster-toolkit.com/mime-types.shtml

    ReplyDelete