Ste*_*erg 4 node.js node-request microsoft-graph-api
我绞尽脑汁(和其他人)试图让它发挥作用。我正在通过 MS Graph API 拉一张照片 - 这部分工作正常。我能够接收数据(以字节为单位)。但是,我无法将图像正确转换为附加为文件并发布。
我已经阅读了几篇关于 SO 和 GH 的帖子,并尝试了大约 10 种不同的 npm 包和风格(btoa、atob 等......出于绝望),包括来自Graph docs的 JS 示例。没有任何解决方案奏效。npm 包都产生彼此不同的输出,当我拍摄照片并上传到在线 base64 转换器时,它们都与输出不匹配。另外,如果我进行在线转换并将输出字符串直接放入代码中,它就可以工作。
这是我的代码的当前迭代。任何帮助,将不胜感激。
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);
}
});
Run Code Online (Sandbox Code Playgroud)
该.sendActivity命令仅采用附件,如下所示:
await dc.context.sendActivity({
attachments: [
{ contentType: photoResponse.ContentType, contentUrl: photoResponse.Base64string }
]
});
Run Code Online (Sandbox Code Playgroud)
当您请求照片的 时/$value,响应将只是图像的原始二进制文件。request然而,客户端utf8默认将正文视为基于字符串。
为了重新训练原始二进制值,您需要明确告知request您不希望这种情况发生。这是通过设置完成的encoding: null。从文档:
encoding- 用于setEncoding响应数据的编码。如果null, 则body作为 返回Buffer。其他任何内容(包括 的默认值undefined)都将作为编码参数传递给toString()(意味着utf8默认情况下这是有效的)。(注意:如果您需要二进制数据,则应设置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);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1445 次 |
| 最近记录: |