SpringMVC文件下载
2020.02.03 16:46
2020.02.03 16:46
1. 文件下载
文件下载就很简单了,我们只需要3个步骤:
1、获取要下载的文件名(是参数)
2、从服务器读取该名字对应的文件
3、输出给浏览器(需要设置响应头)
2. 代码
@Controller
@RequestMapping("/download")
public class DownloadController {
@RequestMapping("/")
public void down(String name, HttpSession session, HttpServletResponse response) {
System.out.println("name = " + name);
String path = session.getServletContext().getRealPath(("/upload"));
String real_path = path + File.separator + name;
//设置响应头
response.setHeader("Content-type", "attachment;filename=" + name);
// 读取目标文件,输出给浏览器
try {
IOUtils.copy(new FileInputStream(real_path), response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
本节阅读完毕!
(分享)