Created
January 17, 2014 19:12
-
-
Save RodrigoEspinosa/8479540 to your computer and use it in GitHub Desktop.
jQuery ajax file upload plugin using FormData JavaScript Object.
This file contains hidden or 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 ($) { | |
$.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