一、利用Servlet实现文件流下载:
1.在工程WebContent/WEB-INF目录创建files目录,并增加待下载文件"a.html",路径:
工程/WebContent/WEB-INF/files/a.html
2.创建处理下载的Servlet:
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
download(req, resp);
}
public void download(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取文件名
String fileName = req.getParameter("fileName");
System.out.println(fileName);
// 获取文件路经
String filePath = getServletContext().getRealPath("WEB-INF/files/" + fileName);
// 设置返回数据类型为文件附件
resp.setHeader("Content-Disposition", "attachment; filename=" + fileName);
// 获取文件流
FileInputStream in = new FileInputStream(filePath);
// 获取输出流
OutputStream out = resp.getOutputStream();
//完成文件流输出(下载)
int len = 0;
byte[] buf = new byte[10240];
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
3.在web.xml中注册Servlet:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0" metadata-complete="true">
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.yyh.hkw.servlet.DownloadServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/DownloadServlet</url-pattern>
</servlet-mapping>
</web-app>
二、调用Servlet,下载文件:
1.在html页面中增加以下代码:
<!-- DownloadServlet是Servlet配置的url -->
<a href="DownloadServlet?fileName=a.html">下载文件</a>