zoukankan      html  css  js  c++  java
  • 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();
    }
    }
  • 相关阅读:
    死啃了String源码之后
    springBoot中Bean的生命周期
    @RequestMapping,@RequsetBody等注解说明
    mybatis的逆向工程的使用
    java中的Arrays这个工具类你真的会用吗
    Search in Rotated Sorted Array leetcode的第33道题
    看了Java的Class的源码,我自闭了
    面试被问了三次的http状态码到底有什么
    搞懂HashMap,这一篇就够了
    十大排序的java实现(配有动图)
  • 原文地址:https://www.cnblogs.com/shihx/p/13217834.html
Copyright © 2011-2022 走看看