Downloading a file from web application

      This post explains developing a web application which allows requestor to download a file. Here web app will have a servlet which streams requested file to requestor. follow the step to develop it using NetBean 6.8

1. Create a web application [ refer previous posts ]

2.Create a Servlet and add the code given below in doGet method

     String filePath =null;
     int length =0;

       //accept file name as parameter
        String fileName = request.getParameter("FILE_NAME");
        InputStream is = getServletContext().getClassLoader().getResourceAsStream("/"+fileName);
        if(is == null){
            PrintWriter writer = response.getWriter();
            writer.append("<html><body><h1> File "+ fileName +"has not Found</h1></body></html>");
            writer.close();
        }

       //set header information
        response.setContentType("application/x-download");
        response.setHeader("content-disposition", "attachment;filename=Test_Downlaod.txt");


        //Stream file content to response
        OutputStream outputStream = response.getOutputStream();
        byte[] bbuf = new byte[100];
        //DataInputStream in = new DataInputStream(new FileInputStream(filePath));
        DataInputStream in = new DataInputStream(is);
        while ((in != null) && ((length = in.read(bbuf)) != -1))
        {
            outputStream.write(bbuf,0,length);
        }

This servlet accept file name as request parameter , gets access to file using getClassLoader().getResourceAsStream  and streams the content.

Main configuration is setting proper header  information of request telling browser that cpntent type is application/x-download and its an attachment.

3. Create file so that it should be present in class path , for this application we are creating sample file under source folder. When we build this application, this file will get copied under classes folder. getClassLoader().getResourceAsStream function looks required file under classes folder.

Create New File

2010-02-19_1811

Final project in Netbean look like as below

2010-02-19_1815

4. Running Servlet – Invoke servlet with FILE_NAME=<file_name> as query string like

http://localhost:8080/FileDownloadWebApp/download?FILE_NAME=Test.txt

You will get Save-as pop-up windows

2010-02-19_1833

Comments

Popular posts from this blog

State Design Pattern by Example

Eclipse command framework core expression: Property tester

Composite Design Pattern by example