Last active
June 24, 2016 12:10
-
-
Save wallacemaxters/7f29b8c8702d06a2afdf to your computer and use it in GitHub Desktop.
This file contains 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 ($) { | |
var defaults = { | |
cache: false, | |
contentType: false, | |
processData: false, | |
type: 'POST', | |
onProgress: new Function, | |
xhr: function (xhr) { | |
var xhr = $.ajaxSettings.xhr(); | |
xhr.upload.addEventListener('progress', function(e) { | |
var percent = parseFloat(((e.loaded / e.total) * 100).toFixed(2)); | |
defaults.onProgress(percent, e); | |
}, false); | |
return xhr; | |
}, | |
}; | |
$.fn.ajaxUpload = function (options) { | |
var formData = new FormData; | |
// if element is a form, find all inputs | |
if (this.is('form')) { | |
var $el = this.find(':input'); | |
} else { | |
var $el = this; | |
} | |
$el.each(function() { | |
var $that = $(this); | |
var name = $that.attr('name'); | |
var files = $that.prop('files'); | |
var value = $that.val(); | |
if (!name) return; | |
// when input not has file, we know that is a common input | |
if (!files) { | |
formData.append(name, value); | |
} else { | |
// Handles single file or multiple file | |
$.each(files, function(i, file) { | |
formData.append(name, file) | |
}); | |
} | |
}) | |
options = $.extend({}, defaults, options, { | |
data: formData | |
}); | |
$.ajax(options); | |
} | |
})( jQuery ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
O uso disso é