标签:
话说现在很多很多项目需要用到文件上传,自从有了HTML5之后,上传就变的超级简单了。HTML5支持多图片上传,而且支持ajax上传,而且支持上传之前图片的预览,而且支持图片拖拽上传,而且还是纯粹利用file控件实现,JS代码寥寥,想不让人称赞都难啊!
html5的上传实现,是需要file控件以及XMLHttpRequest请求。下面是我封装的一个上传插件:
function fileUpload(options) {
var opts = options || {};
var func = function() {};
this.fileInput = opts.fileInput || null;
this.url = opts.url || ‘‘;
this.fileList = [];
this.onFilter = opts.onFilter || function(f) {return f;}; //选择文件组的过滤方法
this.onSelect = opts.onSelect || func; //文件选择后
this.onProgress = opts.onProgress || func; //文件上传进度
this.onSuccess = opts.onSuccess || func; //文件上传成功时
this.onFailure = opts.onFailure || func; //文件上传失败时;
this.onComplete = opts.onComplete || func; //文件全部上传完毕时
this.init();
}
fileUpload.prototype = {
dealFiles: function(e) { //获取要上传的文件数组(用户选择文件后执行)
var files = e.target.files || e.dataTransfer.files;
this.fileList = this.onFilter(files);
for(var i = 0, file; file = this.fileList[i]; i++){ //增加唯一索引值
file.index = i;
}
this.onSelect(this.fileList);
return this;
},
removeFile: function(fileDelete) { //删除某一个文件
var arrFile = [];
for(var i = 0, file; file = this.fileList[i]; i++){
if (file != fileDelete) {
arrFile.push(file);
}
}
this.fileList = arrFile;
return this;
},
removeAll: function() {