Skip to content

Instantly share code, notes, and snippets.

@raytiley
Created March 27, 2013 00:07
Show Gist options
  • Save raytiley/5250470 to your computer and use it in GitHub Desktop.
Save raytiley/5250470 to your computer and use it in GitHub Desktop.
This class uploads to an S3 bucket. And was adapted from this blog post: http://www.ioncannon.net/programming/1539/direct-browser-uploading-amazon-s3-cors-fileapi-xhr2-and-signed-puts/ You need to have an endpoint on your server that will sign your S3 request for you ('covered in the plog post'). To use: App.S3Upload.create({ file: file-from-fil…
App.S3Upload = Ember.Object.extend({
progress: 0,
state: "pending",
bucket: 'your-bucket'
complete: false,
s3url: null,
xhr: null,
file: null,
fileName: function() {
var file = this.get('file');
return file.name;
}.property('file'),
progressStyle: function() {
return 'width: ' + this.get('progress') + '%';
}.property('progress'),
startUpload: function() {
var model = this;
var file = this.get('file');
var jqxhr = $.get('admin/signput?name=' + file.name + '&type=' + file.type + '&bucket=' + this.get('bucket'))
.done(function(url) {
model.set('s3url', url);
model.uploadtoS3();
});
},
uploadtoS3: function() {
this.createCORSRequest();
var xhr = this.get('xhr'),
model = this;
if (!xhr) {
model.set('state', 'CORS not supported');
}
else {
xhr.onload = function() {
if(xhr.status == 200) {
model.set('state', 'Upload Completed');
}
else {
model.set('state', 'Upload error: ' + xhr.status);
}
model.onComplete();
};
xhr.onerror = function() {
model.set('state', 'XHR Error' + xhr.status);
model.onComplete();
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentLoaded = Math.round((e.loaded / e.total) * 100);
model.set('progress', percentLoaded);
model.set('state', percentLoaded == 100 ? 'Finalizing.' : 'Uploading.');
}
};
xhr.setRequestHeader('Content-Type', model.get('file').type);
xhr.setRequestHeader('x-amz-acl', 'public-read');
xhr.send(model.get('file'));
}
},
createCORSRequest: function() {
var xhr = new XMLHttpRequest(),
url = this.get('s3url');
if ("withCredentials" in xhr) {
xhr.open('PUT', url, true);
}
else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open('PUT', url);
}
else {
xhr = null;
}
this.set('xhr', xhr);
},
onComplete: function() {
this.set('complete', true);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment