Search code examples
spring-bootspring-mvchttp-headershttprequest

How to add file as Form data in Http request in spring boot


I'm writing test cases to a controller in spring boot which takes MultipartFile as RequestParam. In the test case method I'm using TestRestTemplate.exchange() to send the request to the controller. I'm not sure how to make the Headers correctly so that I can send the request.

The Postman curl looks like this:

curl --location --request POST 'localhost:9091/response/upload'
--form 'file=@"/home/adityak/Downloads/ClientLog_NEW.txt"'


Solution

  • For file uploading to any service or endpoint

    private String testExchange(File file) {

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    
    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, headers);
    
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "/upload-file",
            HttpMethod.POST,
            requestEntity,
            String.class);
    
    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    }
    return result;
    

    }