3

I'm trying to upload a file to a REST api using feign client. Which is shown below and works fine.

@PostMapping(value = "/test/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<String> upload(@RequestPart(value = "data") MultipartFile zipFile);

In order to create the Multipart file for the update I do this,

public MultipartFile createFile(){
    String zipFilePath = "some/path/to/file";
    File file = new File(zipFilePath);

    FileItem fileItem = new DiskFileItem(FIELD_NAME, Files.probeContentType(file.toPath()), false,
                file.getName(), (int) file.length(), file.getParentFile());
    try (InputStream input = new FileInputStream(file); OutputStream output = fileItem.getOutputStream()){
        IOUtils.copy(input, output);
    }
    return new CommonsMultipartFile(fileItem);
}

Multipart File created from above method is being used when calling the feign client. Instead of creating the CommonsMultipartFile as above and loading it to memory I decided load it to a Resource as below,

public Resource createFile(){
    String zipFilePath = "some/path/to/file";

    Resource resource = new FileSystemResource(zipFilePath );
    return resource;
}

and changed the feign client method as well like this, But It does not work like this in the feign client.

@PostMapping(value = "/test/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<String> upload(@RequestPart(value = "data") Resource zipFile);

I'm getting an error as Status: 409 CONFLICT. Body: Nothing to upload from response of /test/upload endpoint. But then I tried uploading the resource with a rest template which worked fine for the Resource as the file data,

public ResponseEntity<String> uploadFile(Resource file){
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    HttpEntity<Resource> fileResource = new HttpEntity<>(file);
    parts.add("data", fileResource);
    
    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(parts, headers);
        
    ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
}

What reason is that it does not work Passing a Resource type as part data in feign client. I'm using spring spring boot 2.x.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
Shenali Silva
  • 127
  • 3
  • 9

0 Answers0