Skip to content

Instantly share code, notes, and snippets.

@filod
Created July 22, 2012 09:28
Show Gist options
  • Save filod/3159053 to your computer and use it in GitHub Desktop.
Save filod/3159053 to your computer and use it in GitHub Desktop.
jquery img uploader
/**
* @description jquery img 上传插件 for zhihu ~
* @requires [jquery]
* @author filod <ll@zhihu.com>
*/
(function($, undefined) {
var ImgUploader = function(formEl, options) {
this.isie = true ;
this.option = $.extend({}, $.fn.imgUploader.defaults, options)
this.$msg = $('<span></span>')
this.$file = $(this.option.fileCls)
this.$doBtn = $(this.option.doCls)
this.$form = $(formEl).on('uploadchange', $.proxy(this.doneCallback, this));
this.$file.on("change", $.proxy(this.upload, this));
}
ImgUploader.prototype = {
constructor: ImgUploader,
upload: function(e) {
var self = this
if (!self.checkUploadImageType(this.$file.val())) {
self.setMessage("图片不是 . jpg .png 或 .gif 格式,无法上传");
return
}
if(this.isie){
this.$form[0].submit()
return
}
},
postForm: function (e) {
this.$form[0].submit()
return false
},
checkUploadImageType: function(fileName) {
fileName = fileName + "";
if (!fileName || fileName.length < 3) {
return false;
}
fileName = fileName.toLowerCase();
for (var i = this.option.allowType.length - 1; i >= 0; i--) {
if(!endsWith(fileName,this.option.allowType[i])){
continue
}else{
return true
}
};
return false
},
setMessage : function (msg) {
this.$msg.html(msg).insertBefore(this.$form)
},
doneCallback : function(e, data) {
if(data.r === 1){ //上传失败了
this.setMessage(data.msg)
}else if(data.r === 0){
this.setMessage('')
$('.avatar-preview').attr('src',data.msg)
}
}
}
function endsWith(str, suffix) {
var l = str.length - suffix.length;
return l >= 0 && str.indexOf(suffix, l) == l;
}
$.fn.imgUploader = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('scrollspy'),
options = typeof option == 'object' && option
if (!data) {
$this.data('imagloader', (data = new ImgUploader(this,option)))
}
})
}
$.fn.imgUploader.defaults = {
doCls: '.do-upload',
fileCls: '.avatar-file',
allowType : ['jpg','gif','jpeg','png']
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment