1 package org.kuali.ole.servlet;
2
3 import javax.servlet.ServletException;
4 import javax.servlet.ServletOutputStream;
5 import javax.servlet.http.HttpServlet;
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpServletResponse;
8 import java.io.DataInputStream;
9 import java.io.File;
10 import java.io.FileInputStream;
11 import java.io.IOException;
12
13
14
15
16 public class FileDownloadServlet extends HttpServlet {
17 @Override
18 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19 String name = request.getParameter("fileName");
20 String filePath = request.getParameter("filePath");
21 if(filePath!=null && !filePath.trim().isEmpty()){
22 File file1 = new File(filePath);
23 if(file1.exists()){
24 if(file1.isDirectory()){
25 request.setAttribute("filePath",filePath);
26 getServletContext().getRequestDispatcher("/ListingDirectory.jsp").forward(request,response);
27 }else{
28 int BUFSIZE = 4096;
29 {
30
31
32 File file = new File(filePath);
33 int length = 0;
34 ServletOutputStream outStream = response.getOutputStream();
35 response.setContentType("text/html");
36 response.setContentLength((int)file.length());
37 String fileName = (new File(filePath)).getName();
38 response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
39
40 byte[] byteBuffer = new byte[BUFSIZE];
41 DataInputStream in = new DataInputStream(new FileInputStream(file));
42
43
44 while ((in != null) && ((length = in.read(byteBuffer)) != -1))
45 {
46 outStream.write(byteBuffer,0,length);
47 }
48
49
50
51 outStream.flush();
52 }
53 }
54 }
55 }else{
56 request.setAttribute("filePath",filePath);
57 getServletContext().getRequestDispatcher("/ListingDirectory.jsp").forward(request,response);
58 }
59 }
60 }