Skip to content

Instantly share code, notes, and snippets.

@RodrigoEspinosa
Created January 17, 2014 19:12
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 RodrigoEspinosa/8479540 to your computer and use it in GitHub Desktop.
Save RodrigoEspinosa/8479540 to your computer and use it in GitHub Desktop.
jQuery ajax file upload plugin using FormData JavaScript Object.
(function ($) {
$.fn.fileUpload = function (options) {
var opts = $.extend({}, $.fn.fileUpload.defaults, options);
this.on('change', function (event) {
event.preventDefault();
createAjaxRequest(createFormData(this));
});
function createFormData (self) {
var fd = new FormData(),
files = $('#uploader')[0].files;
for (var i=0; i<files.length; i++) {
fd.append('files-' + i, $('#uploader')[0].files[i]);
}
fd.append('location', opts.location);
return fd;
};
function createAjaxRequest (data) {
$.ajax({
url: opts.url,
type: opts.method,
data: data,
processData: false,
contentType: false,
success: function (response) {
if (response.success) {
alert('Files uploaded!');
} else {
console.log('Uploading error: ' + response.error);
}
}
});
};
};
$.fn.fileUpload.defaults = {
url: document.location.href,
location: 'img/uploads',
method: 'POST'
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment