Discussions

Ask a Question
Back to All

Issue uploading attachment via API

I'm writing setting up a simple add on which will take PDFs from Google Drive and attach them to a ServiceM8 Job, for simplicity I'm doing writing all the code via Google Apps Scripts.

It was a lot of trial and error to get to the point I got, however I have now come to a point which I see a few others have gotten to (by looking through the discussion threads here) but none of them seem to show me a final response.

I was able to get to get an Ok message, and after a lot of trialling I have been able to get the PDF document to actually show up on the Job Diary, however upon opening the file it is empty.

I had no luck at all with images, they would not even show up on the Job Diary.

Here is my code:

function createAttachmentRecord() {
const options = {
'method': 'POST',
'headers': {
Accept: 'application/json',
'Content-Type': 'application/pdf',
Authorization: 'Basic email/password'
},
'payload': JSON.stringify({
active: 1,
attachment_name: 'test.pdf',
file_type: '.pdf',
related_object: 'job',
related_object_uuid: '3e31d242-2f15-4dd5-8a87-1d837d817c5b'
})
};
const url = 'https://api.servicem8.com/api_1.0/attachment.json';
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
var obj = response.getAllHeaders();
var newUUID = obj["x-record-uuid"];
getAttachement(newUUID);
Logger.log("New UUID " + newUUID);
}

function getAttachement(newUUID){
var fileToAttach = DriveApp.getFileById('1Yle6cG5EZuk_EMFd7ZE3IIUq72bspxuo');
var type = fileToAttach.getBlob().getContentType();

var fileData = fileToAttach.getBlob().getBytes();

uploadAttachment(newUUID, fileData, type);
}

function uploadAttachment(newUUID, fileData){

const url = 'https://api.servicem8.com/api_1.0/Attachment/' + newUUID + '.file';
const options = {
'method': 'POST',
'headers': {
Accept: 'application/json',
'Content-Type': 'application/pdf',
Authorization: 'Basic email/password'
},
'payload': JSON.stringify({
file: fileData,
active: 1
})
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());

}

Hopefully someone can identify where my mistake is, or guide me with an alternative way of converting the data to binary (which is where I think my problem might be).

Any assistance on this front will be greatly appreciated.