Friday, January 15, 2010

Sending a file as a download using Java

Many times it may be a requirement to send a file from a server to a user as a download which can be saved on the users machine. To send a file as a download to a user all you need is a Servlet and the file which will be sent to the user. Below is a sample code for the Servlet which will send a file as a download.

private static javax.servlet.ServletConfig config;

/* (non-Javadoc)
 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
 */
@Override
public void init(ServletConfig config) throws ServletException 
{
    // TODO Auto-generated method stub
    super.init(config);
    FileDownloadServ.config = config;
}

private void sendFile(String fileName, HttpServletRequest request, HttpServletResponse response)
{
  java.io.File f = null;
  String file;
  
  file = FileDownloadServ.config.getServletContext().getRealPath("/" + fileName);
  f = new java.io.File(file);

  int length = 0;
  javax.servlet.ServletOutputStream op=null; 
  try
  {
      op = response.getOutputStream();
  }
  catch(java.io.IOException ex)
  {
      System.out.println("IOException while opening the output stream\n"+ex);
  } 

  javax.servlet.ServletContext context  = getServletConfig().getServletContext();
  String mimetype = "application/octet-stream";
  response.setContentType(mimetype);
  response.setContentLength( (int)f.length() );

  response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"" );
  //
  //  Stream to the requester.
  //
  byte[] bbuf = new byte[1024];
  try
  {
     java.io.DataInputStream in = new java.io.DataInputStream(new java.io.FileInputStream(f));

     while ((in != null) && ((length = in.read(bbuf)) != -1))
     {
      op.write(bbuf,0,length);
     }

     in.close();
     op.flush();
     op.close();
  }
  catch(java.io.IOException ex)
  {
     System.out.println("IOException while reading file!\n"+ex);
  }
}     

The above method when called from a Servlet's doPost() or doGet() with fileName as parameter will sent the file to the user.

0 comments:

Post a Comment