文件下载需要用两个jar
commons-io-2.2
链接:https://pan.baidu.com/s/1dafwENwC2f0FzWtwF1pMYQ
提取码:l6vu
commons-fileupload-1.3.1
链接:https://pan.baidu.com/s/1r3kejVKTPBvGxHThRVKNJg
提取码:dunu
@Controller
public class DemoController {
@RequestMapping("download")
public void download(String fileName,HttpServletResponse res,HttpServletRequest req) throws IOException{
//设置请求头
res.setHeader("Content-Disposition", "attachment;filename="+fileName);
//
ServletOutputStream os = res.getOutputStream();
//获取文件在电脑中路径
String path = req.getServletContext().getRealPath("files");
//输出路劲
System.out.println(path);
File file = new File(path, fileName);
//读取文本成为二进制流 用的是导入包中的一个工具
byte[] bytes = FileUtils.readFileToByteArray(file);
os.write(bytes);
os.flush();
os.close();
}
}
JSP部分:
<title>test</title>
</head>
<body>
<a href="download?fileName=xiazai.txt">下载</a>
</body>
</html>
测试文件路劲:/test/WebContent/files/xiazai.txt