Last active
December 2, 2016 14:12
-
-
Save johndellavecchia/623c4171ed37973cfca0fd3a152981fe to your computer and use it in GitHub Desktop.
Mandrill API send with multiple attachment file input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// uses FileReader, which is not supported on older browsers | |
// define the files | |
var files = $('#fileInputID')[0].files, count = files.length; | |
// file input validation, only if we actually have files | |
if (count) | |
{ | |
// create an array for the final attachment object values | |
var files_arr = []; | |
// create an array for promises | |
var promises = []; | |
// loop through the files to create objects | |
for (var i = 0; i < files.length; i++) | |
{ | |
// vars for capture | |
var fileResult, obj; | |
// vars for name and type of the files | |
var ft = files[i].type, fn = files[i].name; | |
// reader.onload is async, so create a promise | |
var p = new Promise(function(resolve, reject) { | |
// function to load Reader with callback | |
readerFiles(files[i], function(e) { | |
// get the file content | |
base = e.target.result; | |
// convert to base64, required by mandrill | |
fileResult = base.substr(base.indexOf(',') + 1); | |
// create a new attachment object with the vars needed | |
obj = { | |
type: ft, | |
name: fn, | |
content: fileResult | |
} | |
// push that object to the array | |
files_arr.push(obj); | |
}); | |
resolve(); | |
// error capture with conditionals can be used | |
// if(/* good condition */) { | |
// resolve('success'); | |
// } | |
// else { | |
// reject('failure'); | |
// } | |
}); | |
} | |
// after promises have completed, send | |
p.then(function() { | |
sendForm(files_arr); | |
}).catch(function() { | |
// error | |
}); | |
// create the reader file | |
function readerFiles(files, onLoadCallback) | |
{ | |
var reader = new FileReader(); | |
reader.readAsDataURL(files); | |
reader.onload = onLoadCallback; | |
} | |
} | |
else | |
{ | |
sendForm(); | |
} | |
function sendForm(files_arr) | |
{ | |
$.ajax({ | |
type: 'POST', | |
url: 'https://mandrillapp.com/api/1.0/messages/send.json', | |
data: { | |
// this is for illustration only, don't expose your key in production | |
// create a server side function instead | |
'key': yourkey, | |
'message': { | |
// all other objects as specified by mandrill API | |
'attachments': files_arr | |
} | |
} | |
}) | |
.done(function(response) { | |
// success | |
}) | |
.fail(function(response) { | |
// fail | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment