来自 Graph 的 base64 转换照片显示为损坏的图像

base64 converted photo from Graph displays as broken image

我绞尽脑汁(和其他人)试图让它发挥作用。我正在通过 MS Graph API 拉一张照片 - 这部分工作正常。我能够接收数据(以字节形式)。但是,我无法将图像正确转换为附加文件并发布。

我已经阅读了一些关于 SO 和 GH 的帖子,并尝试了大约 10 种不同的 npm 包和风格(btoa、atob 等......出于绝望),包括来自 [=13= 的 JS 示例].没有解决方案有效。 npm 包都产生彼此不同的输出,并且当我拍照并上传到在线 base64 转换器时,其中 none 匹配输出。此外,如果我采取在线转换并将输出字符串直接放入代码中,则可以。

这是我的代码的当前迭代。任何帮助将不胜感激。

var optionsPhoto = {
  url: "https://graph.microsoft.com/v1.0/me/photo/$value",
  method: "GET",
  headers: {
    Authorization: "Bearer " + token
  }
};

await request(optionsPhoto, function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    photoResponse.data = [
      {
        "@odata.type": "#microsoft.graph.fileAttachment",
        contentBytes: body.split(",").toString("base64"),
        contentLocation: "https://graph.microsoft.com/v1.0/me/photo/$value",
        isinline: true,
        Name: "mypic.jpg"
      }
    ];
    photoResponse.ContentType = response.headers["content-type"].toString();
    photoResponse.Base64string = (
      "data:" +
      photoResponse.ContentType +
      ";base64," +
      photoResponse.data[0].contentBytes
    ).toString();
  } else {
    console.log(error);
  }
});

.sendActivity 命令仅获取附件,如下所示:

await dc.context.sendActivity({
  attachments: [
    { contentType: photoResponse.ContentType, contentUrl: photoResponse.Base64string }
  ]
});

当您请求照片的 /$value 时,响应将只是图像的原始二进制文件。然而,request 客户端默认将正文视为基于 utf8 的字符串。

为了重新训练原始二进制值,您需要明确告诉 request 您不希望这种情况发生。这是通过设置 encoding: null 来完成的。来自文档:

encoding - encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer. Anything else (including the default value of undefined) will be passed as the encoding parameter to toString() (meaning this is effectively utf8 by default). (Note: if you expect binary data, you should set encoding: null.)

代码看起来像这样:

var optionsPhoto = {
  url: "https://graph.microsoft.com/v1.0/me/photo/$value",
  encoding: null, // Tells request this is a binary response
  method: "GET",
  headers: {
    Authorization: "Bearer " + token
  }
};

await request(optionsPhoto, function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    // Grab the content-type header for the data URI
    const contentType = response.headers["content-type"];

    // Encode the raw body as a base64 string
    const base64Body = body.toString("base64");

    // Construct a Data URI for the image
    const base64DataUri = "data:" + contentType + ";base64," + base64Body;

    // Assign your values to the photoResponse object
    photoResponse.data = [
      {
        "@odata.type": "#microsoft.graph.fileAttachment",
        contentBytes: base64Body,
        contentLocation: optionsPhoto.url,
        isinline: true,
        Name: "mypic.jpg"
      }
    ];
    photoResponse.ContentType = contentType;
    photoResponse.Base64string = base64DataUri;
  } else {
    console.log(error);
  }
});