Sunday, February 17, 2013
I have already posted how you can upload a file to server with servlet. Today I will post how to download a file from server with servlet. You know how to send HTML data to client. But there may be situation where client may want to download a file hosted by server. So, here I will write the servlet code that will send the file to the client. The two important things that you will have to remember are :
  • MIME type : You will have to set the content type. This is necessary as Container has no idea about type of file. If the type is set then the browser will automatically open the file in client's default application for that particular type.This is done using response.setContentType() method which takes in MIME type as parameter.
  • I/O stream : You will have to use OutputStream and not PrintWriter. This is because we will be sending binary data and not HTML. This is done using response.getOutputStream() method which returns a reference to the object of
Screenshot of output
Output as seen in Firefox
Java Source Code
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Downloader extends HttpServlet{

    public void doGet(HttpServletRequest req,HttpServletResponse res){
        res.setContentType("application/pdf"); //setting MIME type
        ServletContext ctx = getServletContext();
            //getting stream to file
            InputStream is = ctx.getResourceAsStream("/ALG_3rd.pdf");
            int read = 0;
            byte[] bytes = new byte[1024]; //setting buffer
            OutputStream os = res.getOutputStream();  //getting stream

            while ((read = != -1) //reading file
               os.write(bytes, 0, read);  //writing to stream

            os.flush();  //closing streams
        }catch(Exception e){}

Download Links
DOWNLOAD the project archive from Mediafire
DOWNLOAD the project archive from 4shared
NOTE : The archive does not contain the pdf. So remember to add it while using it.


Post a Comment

Total Pageviews

Subscribe via Email


Popular Posts