Node.js base64从图形转换的照片显示为断开的图像
我(和其他人)绞尽脑汁想让这项计划奏效。我通过MS Graph API拉一张照片-这部分工作正常。我能够接收数据(字节)。但是,我无法将图像正确转换为附加文件并发布 我在SO和GH上读过几篇帖子,也尝试过10种不同的npm包和口味(btoa、atob等,出于绝望),包括来自。没有任何解决办法奏效。npm软件包彼此产生不同的输出,当我拍摄照片并上传到在线base64转换器时,没有一个与输出相匹配。此外,如果我进行在线转换,并将输出字符串直接放入代码中,它就可以工作 这是我代码的当前迭代。任何帮助都将不胜感激Node.js base64从图形转换的照片显示为断开的图像,node.js,microsoft-graph-api,node-request,Node.js,Microsoft Graph Api,Node Request,我(和其他人)绞尽脑汁想让这项计划奏效。我通过MS Graph API拉一张照片-这部分工作正常。我能够接收数据(字节)。但是,我无法将图像正确转换为附加文件并发布 我在SO和GH上读过几篇帖子,也尝试过10种不同的npm包和口味(btoa、atob等,出于绝望),包括来自。没有任何解决办法奏效。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);
}
});
.sendActivity
命令仅获取附件,如下所示:
await dc.context.sendActivity({
attachments: [
{ contentType: photoResponse.ContentType, contentUrl: photoResponse.Base64string }
]
});
当您请求照片的
/$value
时,响应将只是图像的原始二进制文件。但是,请求
客户端默认将主体视为基于utf8
的字符串
为了重新训练原始二进制值,您需要明确地告诉request
,您不希望发生这种情况。这是通过设置编码:null
完成的。从文件中:
encoding
-用于响应数据的setEncoding
的编码。如果null
,则正文
将作为缓冲区
返回。任何其他(包括未定义的默认值)
将作为参数传递给toString()
(这意味着默认情况下这实际上是utf8
)。(注意:如果需要二进制数据,则应设置编码: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);
}
});
先生,你是救命恩人!我今天有一个演讲,有这个是必要的。非常感谢你。