springboot文件下载小demo
一、准备前端页面链接
<a href="../file/download?fileName=xxxx.xxx">xxx.xxx</a>
二、编写Controller
@RequestMapping("/download")
//注意返回值是void,不能响应跳转页面和响应流,只能二选一
public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
//获得下载的资源文件夹
String realPath = request.getRealPath("/upload");
//获得输入流
FileInputStream is = new FileInputStream(new File(realPath, fileName));
//获得输出流
ServletOutputStream os = response.getOutputStream();
//以附件的形式下载
response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
IOUtils.copy(is,os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
总结
注意:响应跳转页面和响应输入流只能选择一个,否则500异常。