问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
@WebServlet("/DownLoadServlet")
public class DownLoadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取请求参数名 filename
String filename = request.getParameter("filename");
System.out.println("参数名:" + filename);
//2.获取文件真实路径,并封装到字节输入流
ServletContext context = getServletContext();
String realPath = context.getRealPath("/download/" + filename);
System.out.println("真是路径:" + realPath);
FileInputStream in = new FileInputStream(realPath);
//3.准备response字节输出流
ServletOutputStream out = response.getOutputStream();
//4.告诉浏览器下载文件的MIME类型
String mimeType = context.getMimeType(filename);
response.setContentType(mimeType);
//5.告知浏览器以附件的形式保存
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
//6.IO的拷贝
byte b[] = new byte[1024*4];
int len;
while ((len = in.read(b)) != -1) {
out.write(b,0,len);
}
//7.释放资源
out.close();
in.close();
}
}
<title>Title</title><h2>文件下载</h2>
<a href="/day07_request_response_1/DownLoadServlet?filename=demo.docx">文档</a>
<a href="/day07_request_response_1/DownLoadServlet?filename=test.zip">压缩包</a>