上一篇博客我们讲述了Spring MVC的文件上传开发,这次我们来看一下Spring MVC的文件下载开发。
文件下载Controller
注意事项:
- 响应头的设置有附加(下载)(attachment)和预览(inline)之分
@GetMapping("/download")
public void fileDownLoad(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取存放文件的绝对路径
String realPath = request.getSession().getServletContext().getRealPath("/files");
//获取指定文件
File file = new File(realPath, filename);
if (!file.exists()) {
throw new RuntimeException("请求的文件不存在!");
}
//获取文件输入流
FileInputStream inputStream = new FileInputStream(file);
//设置响应头 attachment:下载 inline:预览
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
//获取响应输出流对象
ServletOutputStream outputStream = response.getOutputStream();
//进行文件拷贝
IOUtils.copy(inputStream, outputStream);
//关闭资源
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
测试
在浏览器中输入:http://localhost:8080/spring/file/download?filename=gjh.txt