Created
November 23, 2011 13:37
-
-
Save corpix/1388677 to your computer and use it in GitHub Desktop.
FormData html5Uploader
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($){ | |
$.fn.html5Uploader = function(){ | |
return this.each(function(){ | |
var $this = $(this); | |
if($this.is('[type="file"]')){ | |
$this.bind('change', function(){ | |
var files = this.files; | |
for(var i = 0;i < files.length;i++){ | |
fileHandler.call($this, files[i]); | |
} | |
}); | |
}/* else { // TODO пробрасывать в fileHandler input, иначе событие загрузки для файлов, добавленных ддраг н дропом не будет вызываться | |
$this | |
.bind('dragenter dragover', function(){ return false; }) | |
.bind('drop', function(e){ | |
var files = e.originalEvent.dataTransfer.files; | |
for(var i = 0;i < files.length;i++){ | |
fileHandler.call($this, files[i]); | |
} | |
return false; | |
}); | |
}*/ | |
}); | |
function fileHandler(file){ | |
if(!window.FileReader) | |
return $.sticky('Отсутствует компонент FileReader'); | |
if(!window.FormData) | |
return $.sticky('Отсутствует компонент FormData'); | |
var self = this | |
, fileReader = new FileReader(); | |
fileReader.readAsDataURL(file); | |
var formData = new FormData(); | |
formData.append(this.attr('name'), file); | |
$.ajax({ | |
url: self.attr('data-url'), | |
data: formData, | |
context: self, | |
cache: false, | |
contentType: false, | |
processData: false, | |
type: 'POST', | |
success: function(data){ | |
if(!data.error){ | |
var message = self.attr('data-message'); | |
if(message) | |
$.sticky(message); | |
} | |
self.val(''); | |
self.trigger(self.attr('name') + ':res', [data]); | |
} | |
}); | |
} | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment