Created
September 3, 2012 06:14
-
-
Save zhendershot/3607211 to your computer and use it in GitHub Desktop.
REST API Upload to S3 in Titanium
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
function upload(name, file, callback) { | |
Ti.include('lib/sha-aws.js'); // file comes from this URL's project: http://aws.amazon.com/code/Amazon-S3/3236824658053653 | |
Ti.include('lib/webtoolkit.utf8.js'); // code for this file from this URL: http://www.webtoolkit.info/javascript-utf8.html | |
Ti.include('lib/date.js'); // file comes from this URL: http://www.mattkruse.com/javascript/date/source.html | |
var AWSAccessKeyID = appGlobal.config.s3AccessKey; | |
var AWSSecretAccessKey = appGlobal.config.s3SecretKey; | |
var AWSBucketName = appGlobal.config.s3BucketName; | |
var AWSHost = appGlobal.config.s3Host; | |
var currentDateTime = formatDate(new Date(),'E, d MMM yyyy HH:mm:ss') + ' -0600'; | |
var xhr = Ti.Network.createHTTPClient(); | |
xhr.onerror = function(e) { | |
var errorDetails = e.error + '\n'; | |
errorDetails += xhr.responseText; | |
Ti.API.info(errorDetails); | |
}; | |
xhr.onload = function() { | |
Ti.API.info('got my response, http status code ' + this.status); | |
callback.call(); | |
}; | |
//ensure we have time to upload | |
xhr.setTimeout(99000); | |
// true or false if it's asynchronous or not (last parameter below for xhr.open) | |
xhr.open('PUT', 'http://' + AWSHost + '/' + AWSBucketName + '/' + name, false); | |
var StringToSign = 'PUT\n\n\n' + currentDateTime + '\nx-amz-acl:public-read\n/'+AWSBucketName+'/' + name; | |
var AWSSignature = b64_hmac_sha1(AWSSecretAccessKey, Utf8.encode(StringToSign)); | |
var AuthorizationHeader = 'AWS ' + AWSAccessKeyID + ':' + AWSSignature; | |
xhr.setRequestHeader('Authorization', AuthorizationHeader); | |
xhr.setRequestHeader('X-Amz-Acl', 'public-read'); | |
xhr.setRequestHeader('Host', AWSHost); | |
xhr.setRequestHeader('Date', currentDateTime); | |
xhr.send(file); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment