Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save choonkeat/192ce572742bba86697a to your computer and use it in GitHub Desktop.
Save choonkeat/192ce572742bba86697a to your computer and use it in GitHub Desktop.
(function() {
function direct_upload() {
console.log('direct_upload', this);
var ele = this;
new DirectUpload({
file_element: ele,
onProgress: function(percent, message) {
console.log('onProgress', arguments);
},
onError: function(status) {
console.log('onError', arguments);
}
});
}
$(document).on('change', "input[type='file']", direct_upload);
})();
// modified from https://devcenter.heroku.com/articles/s3-upload-node#direct-uploading
(function() {
this.DirectUpload = (function() {
DirectUpload.prototype.onProgress = function(percent, loaded, total) { };
DirectUpload.prototype.onError = function(status) { alert(status); };
function DirectUpload(options) {
if (options == null) options = {};
for (option in options) {
this[option] = options[option];
}
this.handleFileSelect(options.file_element);
}
DirectUpload.prototype.handleFileSelect = function(file_element) {
var f, files, output, _i, _len, _results, url;
this.onProgress(0);
url = $(file_element).data('uploadurl');
files = file_element.files;
output = [];
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
f = files[_i];
_results.push(this.uploadToS3(f, url));
}
return _results;
};
DirectUpload.prototype.createCORSRequest = function(method, url) {
var xhr;
xhr = new XMLHttpRequest();
if (xhr.withCredentials != null) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
};
DirectUpload.prototype.uploadToS3 = function(file, url) {
var this_s3upload, xhr;
this_s3upload = this;
xhr = this.createCORSRequest('PUT', url + (url.indexOf('?') == -1 ? '?' : '&') + 'file=' + encodeURIComponent(file.name));
if (!xhr) {
this.onError('CORS not supported');
} else {
xhr.onload = function(event) {
if (xhr.status === 200) {
this_s3upload.onProgress(100);
console.log(event.target.responseText);
} else {
return this_s3upload.onError('Upload error: ' + xhr.status);
}
};
xhr.onerror = function() {
return this_s3upload.onError('XHR error.');
};
xhr.upload.onprogress = function(e) {
var percentLoaded;
if (e.lengthComputable) {
percentLoaded = Math.round((e.loaded / e.total) * 100);
return this_s3upload.onProgress(percentLoaded, e.loaded, e.total);
}
};
}
return xhr.send(file);
};
return DirectUpload;
})();
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment