Skip to content

Instantly share code, notes, and snippets.

@victorvhpg
Created February 2, 2014 03:05
Show Gist options
  • Save victorvhpg/8762497 to your computer and use it in GitHub Desktop.
Save victorvhpg/8762497 to your computer and use it in GitHub Desktop.
upload de arquivo com jquery ajax - fle upload ajax
(function($){
//=========================================================================================
$.ajaxUpload = function(config) {
var formData = new FormData();
var data = config.data;
for(var i in data){
formData.append(i, data[i]);
}
return $.ajax({
type: "POST",
url: config.url,
//por causa do upload
processData: false,
data: formData, //deve ser do tipo FormData
//por causa do upload
contentType: false,
//sobreescreve o xhr do jquery
xhr: function() {
var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener('progress', config.progressoUpload || (function(e) {
if (e.lengthComputable) {
console.log("Enviando... " + ((e.loaded / e.total) * 100).toFixed(2) + "%");
}
}), false);
return xhr;
},
dataType: config.dataType || "json"
});
};
//======================================================================================
//metodo para pegar o 'File' de um input tipo file
//exemplo de usar: $("arquivo").getArquivo()
$.fn.getArquivo = function(){
if(this.length == 0){
return;
}
var arq = this[0];
if(arq.type.toLowerCase() !== "file"){
throw Error("Tipo do input deve ser 'file'");
}
if(arq.files.length > 0){
return arq.files[0];
}
return;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment