TeeKai
TeeKai

Reputation: 691

RestTemplate POST Image File Request With An auth Token

With the following code

private def uploadImageFile(assetId: String, apiKey: String, authToken: String, file: MultipartFile, hostUrl: String, restTemplate: RestTemplate): ResponseEntity[util.Map[String, String]] = {

  val assignFileToAssetUrl = s"$hostUrl/..."

  var multipartRequest: MultiValueMap[String, Object] = new LinkedMultiValueMap[String, Object]()
  multipartRequest.add("file", file.getBytes)
  multipartRequest.add("name", "file")
  multipartRequest.add("filename", file.getOriginalFilename)
  multipartRequest.add("apiKey", apiKey)
  multipartRequest.add("authToken", authToken)
  println("Created multipart request: " + multipartRequest)

  var  headers: HttpHeaders= new HttpHeaders()
  headers.setContentType(MediaType.MULTIPART_FORM_DATA)

  val request: HttpEntity[Object]  = new HttpEntity[Object](multipartRequest, headers);
  println("request: " + request)

  var messageConverters: util.List[HttpMessageConverter[_]] = new util.ArrayList[HttpMessageConverter[_]]();
  messageConverters.add(new FormHttpMessageConverter());
  messageConverters.add(new MappingJackson2HttpMessageConverter());
  restTemplate.setMessageConverters(messageConverters);

  val httpResponse: ResponseEntity[util.Map[String, String]] = restTemplate.postForEntity(assignFileToAssetUrl, multipartRequest, classOf[java.util.Map[String, String]])
  if (!httpResponse.getStatusCode().equals(HttpStatus.OK)){
    println("Problems with the request. Http status: " + httpResponse.getStatusCode());
  }
  httpResponse
}

The log file shows

2016-07-16 20:47:01.744 DEBUG 4423 --- [nio-8080-exec-1] o.s.web.client.RestTemplate              : Writing [{file=[[B@6abe44a9], name=[file], filename=[TB1YvKKKVXXXXXQXpXXXXXXXXXX-492-660.jpg], apiKey=[...], authToken=[...]}] using [org.springframework.http.converter.FormHttpMessageConverter@230f7e0d]

which indicates The FormHttpMessageConverter is used and it yields a 400 error. If I switch the order of the two message converter being added into the list. The log message will show that the MappingJackson2HttpMessageConverter is used and it yields a 500 error.

What will be the right way to post an image file along with some other data?

The above code is in Scala. I port Java code into Scala. It shall be under stable for Java people.

Updated: I make a change based on the answer without a luck. I still get the 400 error. Notice I replace the "authToken" key with "Authorization". The followings is the changed code:

 private def assignFileToAsset(assetId: String, apiKey: String, authToken: String, file: MultipartFile, hostUrl: String, restTemplate: RestTemplate): ResponseEntity[util.Map[String, String]] = {

   val assignFileToAssetUrl = s"$hostUrl/..."

   var multipartRequest: MultiValueMap[String, Object] = new LinkedMultiValueMap[String, Object]()
   multipartRequest.add("file", file.getBytes)
   multipartRequest.add("name", "file")
   multipartRequest.add("filename", file.getOriginalFilename)
   println("Created multipart request: " + multipartRequest)

   var  headers: HttpHeaders= new HttpHeaders()
   headers.add("apiKey", apiKey)
   headers.add("Authorization", authToken)
   headers.setContentType(MediaType.MULTIPART_FORM_DATA)

   val request: HttpEntity[Object]  = new HttpEntity[Object](multipartRequest, headers);
   println("request: " + request)
   println("Posting request to: " + assignFileToAssetUrl)

   val httpResponse: ResponseEntity[util.Map[String, String]] = restTemplate.postForEntity(assignFileToAssetUrl, multipartRequest, classOf[java.util.Map[String, String]])
   if (!httpResponse.getStatusCode().equals(HttpStatus.OK)){
     println("Problems with the request. Http status: " + httpResponse.getStatusCode());
   }
   httpResponse
 }

Upvotes: 0

Views: 1249

Answers (1)

Tharsan Sivakumar
Tharsan Sivakumar

Reputation: 6531

What I think is you may need to send the access token with the http header and other the parameters and the file content should be sent along the http body. An expected code (not with exact syntax)

@RequestMapping(value = "/yourMapping", method = RequestMethod.POST)
public @ResponseBody String yourMethod(HttpServletRequest request) {

      RestTemplate template = new RestTemplate();
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.MULTIPART_FORM_DATA);
      headers.add("Authorization", authToken);

      LinkedMultiValueMap<String, Object> map =  

                  new LinkedMultiValueMap<>();
      map.add("your_param_key", "your_param_value");
      map.add("files", your_file_content_in_byte_array);

      HttpEntity<LinkedMultiValueMap<String, Object>> 

              requestEntity = new HttpEntity<>(map, headers);

      String response = restTemplate.postForObject

 (uploadFilesUrl, requestEntity, String.class);

}

Please refer following posts for more info.

http://techie-mixture.blogspot.com/2016/07/authentcation-with-rest-template.html

http://techie-mixture.blogspot.com/2016/07/sending-multipart-files-using-spring.html

Upvotes: 1

Related Questions