页面:
<body>
<br>手动编码提供下载。:<br>
<a href="helloServlet?filename=aa.jpg">aa.jpg</a><br>
<a href="helloServlet?filename=bb.txt">bb.txt</a><br>
<a href="helloServlet?filename=cc.rar">cc.rar</a><br>
</body>
sevlet:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getParameter("filename");
//让浏览器收到这份资源的时候, 以下载的方式提醒用户,而不是直接展示。
response.setHeader("Content-Disposition","attachmen;filename="+filename);
//获取这个文件在tomcat里面的绝对路径地址
String realPath = this.getServletContext().getRealPath("download/"+filename);
FileInputStream in = new FileInputStream(realPath);
ServletOutputStream out = response.getOutputStream();
int len = 0;
byte[] arr = new byte[1024];
while((len=in.read(arr))!=-1){
out.write(arr,0,len);
}
in.close();
out.close();
}
文件路径: