在springmvc中实现文件下载一般都是借助HttpServletResponse的getOutputStream()方法实现的,除此之外还可以通过ResponseEntity实现:
@RequestMapping(value = "/downloadxx.do", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> downloadxx(HttpServletRequest request, HttpServletResponse response) throws IOException {
String filePath = "/download/xx.zip";
ClassPathResource file = new ClassPathResource(filePath);
// 文件名编码,解决乱码问题
String fileName = file.getFilename();
// 解决文件名乱码问题
// String fileName = URLEncoder.encode(file.getFilename(), StandardCharsets.UTF_8.toString());
String userAgentString = request.getHeader("User-Agent");
String browser = UserAgent.parseUserAgentString(userAgentString).getBrowser().getGroup().getName();
if (browser.equals("Chrome") || browser.equals("Internet Exploer") || browser.equals("Safari")) {
fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\+", "%20");
} else {
fileName = MimeUtility.decodeText(fileName); // encodeWord(fileName);
}
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename="%s"", fileName));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok().headers(headers).contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
}