1.创建index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
让tomcat的默认servlet去提供下载:<br>
<a href="download/aa.jpg">aa.jpg</a><br>
<a href="download/bb.txt">bb.txt</a><br>
<a href="download/cc.rar">cc.rar</a><br>
<br>手动编码提供下载。:<br>
<a href="DownLoad?filename=aa.jpg">aa.jpg</a><br>
<a href="DownLoad?filename=bb.txt">bb.txt</a><br>
<a href="DownLoad?filename=cc.rar">cc.rar</a><br>
</body>
</html>
2.创建Servlet DownLoad
package com.hbxy.rick;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownLoad extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1. 获取要下载的文件名字 aa.jpg --- inputStream
String fileName = request.getParameter("filename");
// 2. 获取这个文件在tomcat里面的绝对路径地址
String path = getServletContext().getRealPath("download/" + fileName);
// 让浏览器收到这份资源的时候, 以下载的方式提醒用户,而不是直接展示。
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
//response.setStatus(302);
//response.setHeader(Location, "login_success.html");
// response.sendRedirect("login_success.html");
// 3. 转化成输入流
InputStream is = new FileInputStream(path);
OutputStream os = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.close();
is.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
测试
下载成功!!!!!