1.前台请求
<a href="/download/druid配置参数.png">下载druid配置</a>
2.后台
rest风格的下载方式,这里再requestMapping必须加上filename:.+主要解决文件名不全的问题
@RequestMapping("/download/{filename:.+}")
public ResponseEntity download(@PathVariable String filename,HttpSession session) throws Exception {
//1.获取下载的文件路径
String realPath = session.getServletContext().getRealPath("/download/" + filename);
//2.把流输入到程序中
InputStream inputStream = new FileInputStream(realPath);
//3.读取流
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
//4.创建响应头
HttpHeaders httpHeaders = new HttpHeaders();
//解决文件名中文乱码
filename = URLEncoder.encode(filename,"UTF-8");
httpHeaders.add("Content-Disposition","attachment;filename="+filename);
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
inputStream.close();
return responseEntity;
}