I'm developing a web application wrapped in Phonegap to upload recorded videos to Amazon S3. I've done some research, and have concluded there are two ways to do this: use the Amazon AWS JavaScript SDK, or using the Phonegap FileTransfer API (along with the Amazon S3 REST API).
When you capture a video in a PhoneGap application, it's only possible to request the URI to the video file (not the file contents itself). You can use this URI in a FileTransfer to post to S3 like so:
var s3Uploader = (function () {
var s3URI = encodeURI("http://ift.tt/1LKlQib"),
policyBase64 = "YOUR_BASE64_ENCODED_POLICY_FILE",
signature = "YOUR_BASE64_ENCODED_SIGNATURE",
awsKey = 'YOUR_AWS_USER_KEY',
acl = "public-read";
function upload(imageURI, fileName) {
var deferred = $.Deferred(),
ft = new FileTransfer(),
options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileName;
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.params = {
"key": fileName,
"AWSAccessKeyId": awsKey,
"acl": acl,
"policy": policyBase64,
"signature": signature,
"Content-Type": "image/jpeg"
};
ft.upload(imageURI, s3URI,
function (e) {
deferred.resolve(e);
},
function (e) {
deferred.reject(e);
}, options);
return deferred.promise();
}
return {
upload: upload
}
}());
(From http://ift.tt/1gaLwaM)
When you use the AWS SDK, you can upload files like so:
$scope.creds = {
bucket: 'your_bucket',
access_key: 'your_access_key',
secret_key: 'your_secret_key'
}
$scope.upload = function() {
// Configure The S3 Object
AWS.config.update({ accessKeyId: $scope.creds.access_key, secretAccessKey: $scope.creds.secret_key });
AWS.config.region = 'us-east-1';
var bucket = new AWS.S3({ params: { Bucket: $scope.creds.bucket } });
if($scope.file) {
var params = { Key: $scope.file.name, ContentType: $scope.file.type, Body: $scope.file, ServerSideEncryption: 'AES256' };
bucket.putObject(params, function(err, data) {
if(err) {
// There Was An Error With Your S3 Config
alert(err.message);
return false;
}
else {
// Success!
alert('Upload Done');
}
})
.on('httpUploadProgress',function(progress) {
// Log Progress Information
console.log(Math.round(progress.loaded / progress.total * 100) + '% done');
});
}
else {
// No File Selected
alert('No File Selected');
}
}
(From http://ift.tt/1o6bWZu)
I have two questions:
- Is it best to use the Phonegap API or the AWS SDK to achieve this? It's very important that file transfers are reliable, and retry when they would fail. Uploading should also continue in the background (when the app is not shown). I understand that Phonegap uses the core API functions of iOS/Android for their FileTransfer API. This makes me lean towards this approach. The AWS SDK, on the other hand, is written by Amazon and might do error handling better.
- In this second example, the file body itself is used to post to S3. Is it possible to use the file URI to post to S3? E.g. by reading the file with some function?
Aucun commentaire:
Enregistrer un commentaire