Warm tip: This article is reproduced from serverfault.com, please click

can't set profile photo with ms graph

发布于 2020-12-01 21:39:59

I tried the following:

filePath = sourcePath + "ash.jpg";

byte[] fileContent = FileUtils.readFileToByteArray(new File(filePath));
String encodedString = Base64.getEncoder().encodeToString(fileContent);

imagePayload = HttpRequest.BodyPublishers.ofString(encodedString)

def url='https://graph.microsoft.com/v1.0/users/<myuser>/photo/$value';

HttpClient httpClient = HttpClient.newBuilder()
                        .version(HttpClient.Version.HTTP_2)
                        .build();

HttpRequest request = HttpRequest.newBuilder()
                      .uri(URI.create(url))
                      .method("PUT",imagePayload)
                      .header("Content-Type", "image/jpeg")
                      .header("Authorization", "Bearer " + token)
                      .build();

the return keeps telling me :

An internal server error occurred. The operation failed., The file you chose isn't an image. Please choose a different file.

I guess that the payload is wrong, but what does he expect exactly ? the MS Graph documentation states that it should the binary represetation of the jpeg image

with the following:

filePath = sourcePath + "ash.jpg";

file = new File(filePath);

BufferedImage image = ImageIO.read(file);

ByteArrayOutputStream b = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", b);

byte[] jpgByteArray = b.toByteArray();

StringBuilder sb = new StringBuilder();
for (byte by : jpgByteArray)
    sb.append(Integer.toBinaryString(by & 0xFF));

imagePayloadAsString = sb.toString();

imagePayload = HttpRequest.BodyPublishers.ofString(imagePayloadAsString)

I get the binary string with Os and 1s but the webservice still says that my file is not an image. I must confess that I'm confused

Questioner
laloune
Viewed
0
laloune 2020-12-17 06:17:21

I finally got it! what the ms graph service awaits is just the file itself (with the header image/jpeg). So this way I managed to upload the photo:


file = new File(filePath);

imagePayload = HttpRequest.BodyPublishers.ofFile(file.toPath())

as Dev stated, no need to convert it using base64