Servlet code to Download a File + Java

public class DownloadServlet extends javax.servlet.http.HttpServlet implements

        javax.servlet.Servlet {

    static final long serialVersionUID = 1L;

    private static final int BUFSIZE = 4096;

    private String filePath;

   

    public void init() {

        // the file data.xls is under web application folder

        filePath = getServletContext().getRealPath("") + File.separator + "data.xls";

    }

   

    protected void doGet(HttpServletRequest request,

            HttpServletResponse response) throws ServletException, IOException {

        File file = new File(filePath);

        int length   = 0;

        ServletOutputStream outStream = response.getOutputStream();

        ServletContext context  = getServletConfig().getServletContext();

        String mimetype = context.getMimeType(filePath);

       

        // sets response content type

        if (mimetype == null) {

            mimetype = "application/octet-stream";

        }

        response.setContentType(mimetype);

        response.setContentLength((int)file.length());

        String fileName = (new File(filePath)).getName();

       

        // sets HTTP header

        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

       

        byte[] byteBuffer = new byte[BUFSIZE];

        DataInputStream in = new DataInputStream(new FileInputStream(file));

       

        // reads the file's bytes and writes them to the response stream

        while ((in != null) && ((length = in.read(byteBuffer)) != -1))

        {

            outStream.write(byteBuffer,0,length);

        }

       

        in.close();

        outStream.close();

    }

}



Optional:

We define an integer constant BUFSIZE for the size of buffer is used when reading file’s content.
The member variable filePath points to the actual file on server, it is initialized in the init() method of the Servlet, by the following line of code:

Java Code:   

filePath = getServletContext().getRealPath("") + File.separator + "data.xls";


The file name is data.xls and it is placed under the web application folder, so you should remember to put that file there, before testing the application.

We implement the Servlet’s doGet() method which is invoked when user clicks on the download link from the JSP page. In order to send data to the user, we obtain the response’s output stream object:

Java Code:   

ServletOutputStream outStream = response.getOutputStream();


In order to read the file’s content, we creates an instance of the DataInputStream object:

Java Code:  

DataInputStream in = new DataInputStream(new FileInputStream(file));


It’s important that we should set the MIME type for the response:

Java Code:

mimetype = "application/octet-stream";


And add an attribute Content-Disposition for the response’s header:

Java Code: 

response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");


to force the browser displays a download dialog to users.

We read the file’s content and write bytes stream to the response in the while loop:

Java Code:

while ((in != null) && ((length = in.read(byteBuffer)) != -1))

{

    outStream.write(byteBuffer,0,length);

}


When the reading/writing ends, we close the both streams:

Java Code:  

in.close();

outStream.close();


Depending on your application, you may need to perform some tasks before the file is sent to the user, such as writing a log entry, sending an email, etc…