//1.接收用户文件名称
String filename = req.getParameter("filename");
//2.资源文件路径
String realPath = this.getServletContext().getRealPath("/download/" + filename);
//3.创建流对象
FileInputStream read = new FileInputStream(realPath);
ServletOutputStream out = resp.getOutputStream();
//4.设置响应头下载类型
String mimeType = this.getServletContext().getMimeType(filename);
resp.setHeader("Content-Type",mimeType);
resp.setHeader("Content-Disposition","attachment; filename="+filename);
//5.写入(响应)文件,
byte[] bs = new byte[1024];
int len = 0;
while ((len=read.read(bs)) != -1){
out.write(bs,0,len);
}
out.close();
read.close();
原文:https://www.cnblogs.com/M87-A/p/12584445.html