(十) - 下载文件
一. 创建 download.jsp ( name 即为要下载的文件名称)
</head> <body> <a href="${pageContext.request.contextPath}/download/test1?name=sample.txt">下载</a> </body> </html>
二. 创建 DownloadController.java
@Controller @RequestMapping("/download") public class DownloadController { @ RequestMapping("/test1") public void test1(String name, HttpSession session, HttpServletResponse response) throws IOException { String realPath = session.getServletContext().getRealPath("/upload"); String filePath = realPath + "\\" + name; System.out.println("要下载的文件: " + filePath); //设置响应头, 告知浏览器, 要以附件的新试保存文件, filename=浏览器显示的下载文件名 response.setHeader("content-disposition", "attachment;filename=" + name); //响应 IOUtils.copy(new FileInputStream(filePath), response.getOutputStream()); // return null } }
三. 准备好待下载的文件:
四. 操作下载