You are able to use the jQuery ajax $.ajax
function and the FormData
JavaScript API to upload an image file from your Trigger.io mobile app directly to Amazon S3 as you have done on the web.
You will need to perform the following steps:
- Retrieve your file using the
forge.file
API. - Call
forge.file.base64
to return the base64 value for your file's content. - Create a JavaScript
Blob
object from the returned base64 value - Append the
Blob
object to yourFormData
object - Call your
$.ajax
function toPOST
the file to Amazon S3
As an example, once you have retrieved your image file (Step 1), you could use the following uploadImage
function to upload your image to Amazon S3:
function uploadImage(file, awsAccessKeyId, policy, signature, bucket) {
forge.file.base64(file, function (base64String) {
// Create a Blob from a base64 string
var byteCharacters = atob(base64String);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray.buffer], {type: "image/jpeg"});
var fd = new FormData();
fd.append('key', 'test.jpg');
fd.append('acl', 'public-read');
fd.append('Content-Type', 'image/jpeg');
fd.append('AWSAccessKeyId', awsAccessKeyId);
fd.append('policy', policy);
fd.append('signature', signature);
fd.append("file", blob);
$.ajax({
type: 'POST',
url: 'http://' + bucket + '.s3.amazonaws.com/',
processData: false,
contentType: false,
data: fd,
success: function(response) {
alert('Success uploading photo');
},
error: function () {
alert('Problem uploading photo');
}
});
});
}