1

I meet a request to upload files with spring resttemplate to upload files with http header "multipart/form-data", also some other normal parameters need to be posted. how to implements that?

3 Answers 3

3

You can use the following code in your application to have both multipart-file and normal request parameters at the same time:

Note:

  • replace the URL with your own
  • replace parameter names and values according to your normal parameters
String url = "http://example.com"; String fileAbsPath = "absolute path of your file"; String fileName = new File(fileAbsPath).getName(); Files.readAllBytes(Paths.get(fileAbsPath)); MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>(); ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(Paths.get(fileAbsPath))) { @Override public String getFilename() { return fileName; } }; data.add("file", resource); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("file","application/pdf"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) .queryParam("param1", "value1") .queryParam("param2", "value2"); HttpEntity<> entity = new HttpEntity<> (data, requestHeaders); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> result =restTemplate.exchange( builder.toUriString(), HttpMethod.POST, entity, String.class ); System.out.println(result.getBody()); 
Sign up to request clarification or add additional context in comments.

1 Comment

I too had this issue, i tried it but i am getting: Caused by: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
1

you can use this code.

 HttpHeaders headers = getCASHeaders(MediaType.MULTIPART_FORM_DATA); LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>(); params.add("fileField", new FileSystemResource(""));//get file resource params.add("stringfield", stringPayload); HttpEntity requestEntity = new HttpEntity<>(params, headers); ResponseEntity<CasAssetApiResponse> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); 

This will send post call with two param, you can add more according to your wish.

Please have a look at this stackoverflow answer as well

1 Comment

but in this way,the value of 'stringfield' is a LinkedList, not a String...., their api does recognize the value...
0

I got the error "cannot be cast to java.lang.String" although my code does not have any casting.

enter image description here

1 Comment

This is not an answer to the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.