eureka 经过网关transferRequest下载文件,用form表单、a标签或location下载,ajax不支持文件流,只支持字符串类型xml、json


/**
* Rest模板对象,用于http访问
* 当前对象已经使用@LoadBanlnced 实现的负载均衡
*/
@Autowired
@Qualifier("siteRestTemplate")
RestTemplate restTemplate;

//网关接口
@RequestMapping("/transferRequest/download")
public void transferRequest(String action, String site, String params, String method, Integer timeout, HttpServletResponse httpServletResponse) {
//这里只需要把服务提供者的applicaitonName和接口名称写上即可
String url = "http://" + site + action;
HttpHeaders headers = getHttpHeadersByRequest(request);
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap postParams = getPostParams(params);
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity(postParams, headers);
HttpMethod requestMethod = "GET".equals(method) ? HttpMethod.GET : HttpMethod.POST;
  //如果改用实体类接收,文件的二进制数组会自动转换为字符串,需要重新转换为文件二进制数组,暂时没找到办法转换
ResponseEntity<byte[]> response = restTemplate.exchange(url, requestMethod, httpEntity, byte[].class);
LOGGER.info("中转请求返回:" + response.getStatusCode() + " | " + response.getBody());
try {
HttpHeaders obj = response.getHeaders();
String filename = String.valueOf(obj.get("filename"));
if(filename != null && filename.length()>0){
filename = filename.replace("[","").replace("]","");
}
      //下载接口已经已经处理中文乱码,此处不能再处理,否则会显示不了中文
httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" +filename);

OutputStream outputStream = httpServletResponse.getOutputStream();
outputStream.write(response.getBody());
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

}

  //下载接口
  @RequestMapping("/liu")
@ResponseBody
public void liu(HttpServletResponse response, HttpServletRequest request){
try {
File file = new File("D:\ytzz\yulin\excleFilePath\登记台账2020-05-21-18-06-53.xls");
byte[] bytes = FileUtils.readFileToByteArray(file);
response.setHeader("filename", URLEncoder.encode(file.getName(), "UTF-8"));
response.getOutputStream().write(bytes);
response.getOutputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
原文地址:https://www.cnblogs.com/shihx/p/13217834.html