在Angular 9中向MS Graph电子邮件发送附加文件的问题



我正在向Angular 9 web应用程序添加文件附件功能,但遇到了一个问题。

MSGraphneneneba API参考说,任何文件在使用之前都应该基于64编码,我已经这样做了,但我得到了以下错误

{"错误"{>代码":"RequestBodyRead","message":"无法转换literal‘data:application/pdf;base64,JV……'到所需类型"Edm.Binary"。"}}

这是我的代码;

getBase64(file: File) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
async sendEmail(toEmail: string, subject: string, message: string, fileAttachment: File): Promise<any> {
this.getBase64(fileAttachment).then(
async data => {
// console.log(data)
try {
const sendMail = {
message: {
subject: subject,
body: {
contentType: 'HTML',
content: message
},
toRecipients: [
{
emailAddress: {
address: toEmail
}
}
],
attachments: [
{
"@odata.type": "#microsoft.graph.fileAttachment",
"name": fileAttachment.name,
"contentType": fileAttachment.type.toString,
"contentBytes": data
}
]
}
};
let res = await this.client.api('/me/sendMail').post(sendMail);
return res;
} catch (error) {
this.handleError(error);
}
}
);
}

如果有人能帮忙,我将不胜感激。我已经为此工作了一段时间,但没能解决这个问题。

非常感谢,

马克。

更新:

使用MS Graph Explorer发送电子邮件,我能够确定问题的原因;它是getBase64"data:application/pdf;base64"返回值的第一部分如果我从base64字符串中删除这个,我可以给自己发一封电子邮件。

所以问题是,为什么字符串的第一部分在那里?当getBase64的返回值是未知类型时,我该如何去掉它?

您可以有一个单独的函数来使用promise获取文件的base64编码,然后使用split函数删除第一部分。

<input name="attachments" type="file" (change)="addattachment($event)" >
function getBase64(file, onLoadCallback) {
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onload = function() { resolve(reader.result); };
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
async addattachment (event) {
const myfile = event.target.files[0]
const promise = this.getBase64(myfile)
const base64file = await promise
var ms_base64file = base64file.split(',')[1]
console.log(ms_base64file)
}

最新更新