使用SpringMVC的ResponseEntity方式下载文件

ResponseEntity 下载文件,需要传入3个参数,分别是:请求体、请求头和状态码
可根据返回值返回 byte[]、或String类型


@RequestMapping("/exportCert/{container}")
public ResponseEntity<String> exportCert(@PathVariable("container") String container, HttpServletRequest request) throws Exception {

 String fileName = "C:\\Users\\TEMP_RA.xls";
HttpHeaders headers = setFileDownloadHeader(request, fileName );

 String cert = serverService.downloadServerCert(container);
 return new ResponseEntity<String>(cert,headers,HttpStatus.OK);
}
 
// 设置响应头
 protected HttpHeaders setFileDownloadHeader(HttpServletRequest request, String fileName) {
 String encodedfileName = null;
 try {
  String agent = request.getHeader("User-Agent");
  if (null != agent) {
   agent = agent.toLowerCase();
   if (agent.contains("firefox") || agent.contains("chrome") || agent.contains("safari")) {
    encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
   } else if (agent.contains("msie")) {
    encodedfileName = URLEncoder.encode(fileName,"UTF-8");
   } else if (agent.contains("opera")) {
    encodedfileName = fileName;
   } else {
    encodedfileName = URLEncoder.encode(fileName,"UTF-8");
   }
  }
 } catch (UnsupportedEncodingException e) {
  logger.error("文件{0}字符集转换失败",fileName);
 }
 HttpHeaders headers = new HttpHeaders();
 headers.setContentDispositionFormData("attachment", encodedfileName);
 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
 return headers;
}






猜你喜欢

转载自blog.csdn.net/qq_25619743/article/details/80394752