I am trying to upload a PDF file to a Asana task as an attachment on Google App Script.
The PDF file is from Gmail attachment and I can get the file on my script like below.
var searchMail = GmailApp.search(condition);
var messeges = GmailApp.getMessagesForThreads(searchMail);
for(var i = 0; i < messeges.length; i++) {
for(var j = 0; j < messeges[i].length; j++) {
var attach = messeges[i][j].getAttachments();
}
}
I tried this script to attach the file to a task but the error ‘The request body does not conform to the specification for multipart/form-data
encoding.’ returned.
What should I do?
Thank you.
function addAttachmentToAsanaTask(taskId, attachment) {
const url = `https://app.asana.com/api/1.0/tasks/${taskId}/attachments`;
const boundary = "-------314159265358979323846";
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
let contentType = attachment.getContentType();
let fileName = attachment.getName();
let base64Data = Utilities.base64Encode(attachment.getBytes());
let body = delimiter +
'Content-Type: application/json; charset=UTF-8\r\n\r\n' +
JSON.stringify({"file": fileName}) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Disposition: attachment; filename="' + fileName + '"\r\n' +
'Content-Transfer-Encoding: base64\r\n\r\n' +
base64Data +
close_delim;
const options = {
method: "post",
contentType: "multipart/form-data; boundary=" + boundary,
payload: body,
headers: {"Authorization": "Bearer " + token},
muteHttpExceptions: true
};
const response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
addAttachmentToAsanaTask(taskId, attach[0]);