Reputation: 265
I'm adding file attachment functionality to an Angular 9 web app but have run into an issue.
The MS Graph API reference says that any file should be based64 encoded before being used and I've done this but I get the following error
{"error":{"code":"RequestBodyRead","message":"Cannot convert the literal 'data:application/pdf;base64,JV.....' to the expected type 'Edm.Binary'."}}
Here's my code;
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);
}
}
);
}
If anyone can help I'd greatly appreciate it. I've been working on this for some time now and not been able to solve the issue.
Many thanks,
Mark.
UPDATE:
Using the MS Graph Explorer to send an email I was able to determine the cause of the issue; It's the first part of the returned value from getBase64 "data:application/pdf;base64"
If I remove this from the base64 string I can send an email to myself.
So the question is, why is this first part of the string there and how do I strip it out when the return value from getBase64 is an unknown type?
Upvotes: 0
Views: 1042
Reputation: 71
You can have a separate function to get the base64 encoding of the file using promises, then use the split function to remove that first part.
<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)
}
Upvotes: 1