1
//DownloadServlet.java
package com.demo;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.OutputStream;
9
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 public class DownloadServlet extends HttpServlet {
16 @Override
17 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
18 throws ServletException, IOException {
19 // 获取项浏览器输出的对象
20 OutputStream out = resp.getOutputStream();
21 InputStream in = null;
22 //1- 获得浏览器请求下载的文件名称
23 String fname = req.getParameter("fileName");
24 //2- 判断文件名是否为空
25 if (fname == null) {
26 //如果为空,则提醒用户输入文件名称
27 out.write("<center><font size='36' color='red'>please input fileName = </font></center>".getBytes());
28 return;
29 }
30 //3- 文件名不为空,则判断该文件名是否在指定目录中
31 String absPath = this.getServletContext().getRealPath("/WEB-INF/store");
32
33 File store = new File(absPath);
34 //3-1 得到文件夹中所有文件对象
35 File [] fs = store.listFiles();
36 //遍历store文件夹中的所有文件夹
37 for (File f : fs) {
38 //判断没个File对象,且文件名称和请求的名称相同
39 if (!(f.isFile() && f.getName().equals(fname))) {
40 //如果不符合,则告诉浏览器,文件没有找到
41 out.write("<center><font size='36' color='red'> file not exist, please revisit </font></center>".getBytes());
42 out.close();
43 return;
44 }
45 //4- 满足条件,则获得输入流对象,读取文件
46
47 in = this.getServletContext().getResourceAsStream("/WEB-INF/store/" + fname);
48 //5- 设置正文的MIME类型
49 int length = in.available();//获取正文长度
50 resp.setContentType("application/force-download");
51 //设置响应正文的长度
52 resp.setHeader("Content-Length",length +"");
53 //Content-Disposition:表示为下载的文件提供一个默认的文件名.
54 resp.setHeader("Content-Disposition", "attachment;fileName=" + fname);
55 //6- 读取并发送文件给浏览器
56 byte[] buffer = new byte[length];
57 in.read(buffer);//读取
58
59 out.write(buffer);//发送
60 out.close();
61 in.close();
62 }
63
64 }
65 }
1
//web.xml中的配置
<servlet-name>download</servlet-name>
2 <servlet-class>com.demo.DownloadServlet</servlet-class>
3 </servlet>
4 <servlet-mapping>
5 <servlet-name>download</servlet-name>
6 <url-pattern>/download</url-pattern>
7 </servlet-mapping>