I have a problem uploading a user's photo using the REST API. I follow the documentation
https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/intro_input.htm#fileUploadExample
but I get this debug message:
Response status: Bad Request
Response body: [{"errorCode":"INVALID_FIELD","message":"The file you uploaded doesn't appear to be a valid image."}]
I'm trying to transfer profile photos between two sandboxes. Other simple REST API scripts work so the problem is not the connection.
below is the code I use:
String endpoint = URL + '/services/data/v59.0/connect/user-profiles/[userId]/photo';
String boundary = 'a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq';
String photoDataBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII';
String body = '--' + boundary + '\n';
body += 'Content-Type: application/json; charset=UTF-8\n';
body += 'Content-Disposition: form-data; name="json"\n\n';
body += '{ "cropX" : "0", "cropY" : "0", "cropSize" : "200" }\n';
body += '--' + boundary + '\n';
body += 'Content-Disposition: form-data; name="fileUpload"; filename="myPhoto.jpg"\n';
body += 'Content-Type: application/octet-stream; charset=ISO-8859-1\n\n';
body += photoDataBase64 + '\n';
body += '--' + boundary + '--\n';
HttpRequest request = new HttpRequest();
request.setMethod('POST');
request.setEndpoint(endpoint);
request.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
request.setBody(body);
Http http = new Http();
HttpResponse response = http.send(request);
System.debug('Response status: ' + response.getStatus());
System.debug('Response body: ' + response.getBody());
for testing purposes I use this site to convert an image to base64: https://codebeautify.org/image-to-base64-converter
Normally i will use this:
User u = [Select FullPhotoUrl From User where id = :Userinfo.getUserid()];
PageReference ref = new PageReference(u.FullPhotoUrl);
Blob b = ref.getContent();
String photoDataBase64 = EncodingUtil.base64Encode(b);