使用RestTemplate上传文件给远程接口

MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
     MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
    try {
        ByteArrayResource is = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }
        };
        form.add("file", is);
    } catch (IOException e) {
        e.printStackTrace();
    }
    //设置发送文件和其它参数
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("multipart/form-data");
    headers.setContentType(type);
    HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
    String url = "http://xxx:9090/file/uploadFile";
    ResponseEntity<Map> result = restTemplate.exchange(url, HttpMethod.POST, files, Map.class);  

必须重写getFilename方法,不然回报"Required request part 'file' is not present"错误。

标签: none