AnsweredAssumed Answered

Uploading a file results in 422 Unprocessable Entity

Question asked by Komsant Tivong on May 4, 2018


I've Java code generating pdf files (array of bytes) based on loaded data from the database. Now I'm trying to extend this code so that it uploads this generated file to Sugar. I found a way how to create a Note, so let's assume I've following:

  • String noteId
  • String accessToken
  • byte[] file


The method for uploading:

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.web.client.RestTemplate;
import org.apache.commons.codec.binary.Base64;

public void uploadFile(String noteId, byte[] file, String accessToken) {
     SugarCrmFileUploadRequest requestBody = new SugarCrmFileUploadRequest();
     requestBody.setFilename(Base64.encodeBase64String(file)); // I also tried without encoding

     HttpHeaders requestHeaders = new HttpHeaders();
     requestHeaders.add("oauth-token", accessToken);

     HttpEntity<SugarCrmFileUploadRequest> request = new HttpEntity<>(requestBody, requestHeaders);
     try {
          new RestTemplate().postForLocation(sugarCrmUrl + "/Notes/" + noteId + "/file/filename", request);
     } catch (Exception e) {
          LOGGER.error("sugar failed", e);// here I get 422 Unprocessable Entity

SugarCrmFileUploadRequest is my custom bean containing only those four attributes:

import com.fasterxml.jackson.annotation.JsonProperty;

public class SugarCrmFileUploadRequest {

     private String filename;

     private String oauthToken;

     private String format = "sugar-html-json";

     private boolean deleteIfFails = true;

     // getters, setters


Generated file itself is correct - I can save it on the disk and open it without any problems.


I was searching for any ideas on google and also here in the community but found only some articles which didn't help me (either it's in php or it solves different problems or it doesn't have any solution). As I was quite desperate, I tried also to send it as a (I changed SugarCrmFileUploadRequest.filename from String to File) but got the same result - 422 Unprocessable Entity:

org.springframework.web.client.HttpClientErrorException: 422 Unprocessable Entity
     at org.springframework.web.client.DefaultResponseErrorHandler.handleError(
     at org.springframework.web.client.RestTemplate.handleResponse(
     at org.springframework.web.client.RestTemplate.doExecute(
     at org.springframework.web.client.RestTemplate.execute(
     at org.springframework.web.client.RestTemplate.postForLocation(

If anybody has solution, could you post it here, please? I think it'd help also in this community article where Brayan tries to upload the file in a similar way.


Thank you