001package org.kuali.ole.servlet;
002
003import javax.servlet.ServletException;
004import javax.servlet.ServletOutputStream;
005import javax.servlet.http.HttpServlet;
006import javax.servlet.http.HttpServletRequest;
007import javax.servlet.http.HttpServletResponse;
008import java.io.DataInputStream;
009import java.io.File;
010import java.io.FileInputStream;
011import java.io.IOException;
012
013/**
014 * Created by sheiksalahudeenm on 6/11/14.
015 */
016public class FileDownloadServlet extends HttpServlet {
017    @Override
018    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
019        String name = request.getParameter("fileName");
020        String filePath = request.getParameter("filePath");
021        if(filePath!=null &&  !filePath.trim().isEmpty()){
022            File file1 = new File(filePath);
023            if(file1.exists()){
024                if(file1.isDirectory()){
025                    request.setAttribute("filePath",filePath);
026                    getServletContext().getRequestDispatcher("/ListingDirectory.jsp").forward(request,response);
027                }else{
028                    int BUFSIZE = 4096;
029                    {
030
031                        //System.out.println("kanhiii"+filePath);
032                        File file = new File(filePath);
033                        int length   = 0;
034                        ServletOutputStream outStream = response.getOutputStream();
035                        response.setContentType("text/html");
036                        response.setContentLength((int)file.length());
037                        String fileName = (new File(filePath)).getName();
038                        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
039
040                        byte[] byteBuffer = new byte[BUFSIZE];
041                        DataInputStream in = new DataInputStream(new FileInputStream(file));
042
043
044                        while ((in != null) && ((length = in.read(byteBuffer)) != -1))
045                        {
046                            outStream.write(byteBuffer,0,length);
047                        }
048
049                        // in.close();
050                        // outStream.close();
051                        outStream.flush();
052                    }
053                }
054            }
055        }else{
056            request.setAttribute("filePath",filePath);
057            getServletContext().getRequestDispatcher("/ListingDirectory.jsp").forward(request,response);
058        }
059    }
060}