servlet文件:
package content;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获得要下载的文件名称
String filename = request.getParameter("filename");
// 要下载的这个文件的类型---客户端通过文件的MIME类型去区分类型
response.setContentType(this.getServletContext().getMimeType(filename));
// 告诉客户端文件不是直接解析,而是以附件的形式打开(下载)
response.setHeader("Content-Disposition", "attachment;filename="+filename);
// 获取文件的绝对路径
String path = this.getServletContext().getRealPath("download/"+filename);
// 获得文件输入流
InputStream in = new FileInputStream(path);
// 获取文件输出流----通过response获得的输出流 用于向客户端写内容
ServletOutputStream out = response.getOutputStream();
// 文件拷贝的代码实现
int len = 0;
byte[] buffer = new byte[1024];
while((len = in.read(buffer)) > 0){
out.write(buffer, 0, len);
}
in.close();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
html配置文件:down.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>使用服务器端编码的方式实现文件下载</h1>
<a href="/WEB14/downloadServlet?filename=a.jpg">a.jpg</a><br>
<a href="/WEB14/downloadServlet?filename=a.MOV">a.MOV</a><br>
<a href="/WEB14/downloadServlet?filename=a.mp3">a.mp3</a><br>
<a href="/WEB14/downloadServlet?filename=a.txt">a.txt</a><br>
<a href="/WEB14/downloadServlet?filename=a.zip">a.zip</a><br>
</body>
</html>