当前位置:   article > 正文

RestTemplate远程调用文件上传-multipart/form-data_multiparthttprequst 远程调用

multiparthttprequst 远程调用

RestTemplate远程调用文件上传-multipart/form-data

文件上传

需要有header和form表单上传文件的情况

    @Resource
    private RestTemplate restTemplate;
/**
     * 文件上传到远端的服务器
     * @return
     */
    @PostMapping("/uploadFile")
    @ResponseBody
    public String uploadFile() {

        String result = null;
        try {
            String accessToken = "your token";
            String URL = "your url";

            //设置请求
            HttpHeaders headers = new HttpHeaders();
            String token = YhtTokenUtil.getInstance().getYhtToken();

            headers.add("your_token_key", token);
            headers.add("Content-Type", "multipart/form-data");

            //设置请求体,注意是LinkedMultiValueMap
            MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
            File youFile = new File("D:\\you_path\\file.txt");
            form.add("file", new FileSystemResource(youFile));
//            form.add("your_form_file_key_of_httpRequest", new FileSystemResource(youFile));


            //封装请求报文
            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

            result = restTemplate.postForObject(URL, files, String.class);
            log.debug("result is " + result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号