1. 访问资源响应头如果没有设置Content-Disposition,浏览器默认按照inline值进行处理
1.1 inline:能显示就显示,不能显示就下载
2. 只需要修改响应头中Content-Disposition=”attachment;fileName=文件名”
2.1 attachment:下载,以附件方式下载
2.1 fileName=文件名:就是下载时显示的下载文件名
3. 实现步骤:
3.1 导入apatch的两个jar包
3.2 在jsp中添加超链接,设置要下载的文件
3.2.1 在SpringMVC中放心静态资源文件files
<a href="download?fileName=aaa.txt">下载</a> |
<!-- 静态资源 --> <mvc:resources location="/files/" mapping="/files/**"> </mvc:resources> |
3.3 编写控制器方法
@RequestMapping("/download") public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException{ //设置响应流文件进行下载 response.setHeader("Content-Disposition", "attachment;filename="+fileName); ServletOutputStream os = response.getOutputStream(); String path = request.getServletContext().getRealPath("files"); File file = new File(path,fileName); //转换成二进制放入响应流中 byte[] bytes = FileUtils.readFileToByteArray(file); os.write(bytes); os.flush(); os.close(); } |