加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
imgUpload.js 9.29 KB
一键复制 编辑 原始数据 按行查看 历史
NullFeng 提交于 2017-08-28 11:23 . 初始版本
function ImageUpload(params) {
if(!params.bind)
return;
var files = {};
var file_index = 0;
var limitCount = params.limit || 1;
var uploadUrl = params.uploadUrl;
var bindEl = document.querySelectorAll(params.bind);
var post_data = null;
var maxSize = 1024*1024*3;//默认3M
var container = document.createElement("div");
container.className = "imgUpload";
container.innerHTML = '<div class="imgUpload-stage">'+
'<div class="imgUpload-box">'+
'<h5 class="imgUpload-title">图片上传</h5>'+
'<div class="imgUpload-imgs"></div>'+
'<div style="clear:both"></div>'+
'<div class="imgUpload-fn">'+
'<a class="imgUpload-cancel" style="background:#C6D1DA;color:#333" href="javascript:;">关闭</a><a class="imgUpload-add" href="javascript:;">添加</a><a class="imgUpload-start" href="javascript:;">上传</a>'+
'</div>'+
'<span class="imgUpload-progressbar"></span>'+
'</div>'+
'</div>';
document.body.appendChild(container);
var imgs = container.querySelector(".imgUpload-imgs");
var progressbar = container.querySelector(".imgUpload-progressbar");
var state = container.querySelector(".imgUpload-info");
if(params.maxSize){
var tmp = params.maxSize;
if(tmp.indexOf('mb')!=-1||tmp.indexOf('m')!=-1){
maxSize = parseInt(tmp)*1024*1024;
}
else if(tmp.indexOf('kb')!=-1||tmp.indexOf('k')!=-1){
maxSize = parseInt(tmp)*1024;
}
else if(tmp.indexOf('b')!=-1||tmp.indexOf('b')!=-1){
maxSize = parseInt(tmp)
}
}else{
params.maxSize = "3mb";
}
for(var k=0;k<bindEl.length;k++){
bindEl[k].readOnly = true;
bindEl[k].placeholder = "单击上传图片";
bindEl[k].onclick = function(){
container.style.display = "block";
post_data = this;
init();
}
}
container.querySelector(".imgUpload-cancel").onclick = function(){
files = {};
file_index = 0;
imgs.innerHTML = "";
container.style.display = "none";
progressbar.innerText = "";
}
container.querySelector(".imgUpload-add").onclick = function(){
if(Object.keys(files).length>=limitCount){
alert("只允许上传"+limitCount+"张图片!");
return;
}
var file_input = document.createElement('input');
file_input.type = "file";
file_input.multiple = limitCount == 1 ? false : true;
file_input.click();
file_input.onchange = function(){
if (typeof(FileReader) === 'undefined') {
console.log("抱歉,当前浏览器不支持 FileReader!");
return false;
}
var _this = this;
for(var i=0;i<this.files.length;i++){
var reader = new FileReader();
reader.readAsDataURL(this.files[i]);
(function(index){
reader.onload = function(e){
var newFile = {
obj:_this.files[index],
src:this.result,
info:"未上传",
size:formatFileSize(_this.files[index].size)
};
if(_this.files[index].size>maxSize){
alert("图片文件过大!最多只能"+params.maxSize);
return;
}
if(!/(.jpg|.png|.bmp|.gif|.jpeg|.svg)$/.test(_this.files[index].name)){
alert(_this.files[index].name+"非图片文件");
return;
}
for(var j in files){
if(files[j].src==newFile.src){
console.log(_this.files[index].name+"文件重复");
return;
}
}
files["file_"+file_index] = newFile;
console.log(files);
file_index++;
if(index+1==_this.files.length){
progressbar.innerText = ""+file_index+"张图片";
setTimeout(generateImages,200);
}
}
})(i);
}
}
};
function init(){
if(post_data!=null&&post_data.value.length!=0){
var arr = post_data.value.split('|');
files = {};
for(var l in arr){
files['file_'+l] = {
src:arr[l],
info:'已上传',
size:''
};
}
file_index = l+1;
generateImages();
}
}
function remove(id){
delete files[id];
imgs.removeChild(document.getElementById(id));
for(var m in files){
var arr = [];
if(!files[m].obj){
arr.push(files[m].src);
}
if(arr.length>0)
post_data.value = arr.join('|');
}
if(Object.keys(files).length==0)
post_data.value = "";
console.log(post_data.value);
}
function generateImages(){
imgs.innerHTML = "";
for(var i in files){
var uItem = document.createElement("div");
uItem.className = "imgUpload-item";
uItem.id = i;
var uItem_img = document.createElement("img");
uItem_img.src = files[i].src;
uItem_img.title = files[i].info+files[i].size;
var uItem_del = document.createElement("a");
uItem_del.href = "javascript:;";
uItem_del.innerText = "删除";
var uItem_info = document.createElement("div");
uItem_info.className = "imgUpload-info";
uItem_info.innerText = files[i].info;
(function(index){
uItem_del.onclick = function(){remove(index);};
})(i);
uItem.appendChild(uItem_img);
uItem.appendChild(uItem_del);
uItem.appendChild(uItem_info);
imgs.appendChild(uItem);
}
}
function formatFileSize(fileSize) {
if (fileSize < 1024) {
return fileSize + 'B';
} else if (fileSize < (1024*1024)) {
var temp = fileSize / 1024;
temp = temp.toFixed(2);
return temp + 'KB';
} else if (fileSize < (1024*1024*1024)) {
var temp = fileSize / (1024*1024);
temp = temp.toFixed(2);
return temp + 'MB';
} else {
var temp = fileSize / (1024*1024*1024);
temp = temp.toFixed(2);
return temp + 'GB';
}
}
container.querySelector(".imgUpload-start").onclick = function(){
var formData = new FormData();
var fileCount = 0;
for(var i in files){
if(files[i].obj){
fileCount++;
formData.append("file[]",files[i].obj);
}
}
if(fileCount==0){
alert("没有选择任何文件!");
return;
}
$.ajax({
url:uploadUrl,
data: formData,
type: "post",
dataType: "json",
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
progressbar.innerText = "开始上传...";
},
xhr: function () {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', function (e) {
var percent = (e.loaded / e.total * 100).toFixed(2);
progressbar.innerText = (percent + "%");
}, false);
}
return myXhr;
},
success:function(result){
console.log(result);
if(result.state==1){
if(post_data!=null){
if(post_data.value.length>0)
result.path = post_data.value+"|"+result.path;
post_data.value = result.path;
params.callback && params.callback(result.path);
console.log("files => ",files);
result.msg && alert(result.msg);
init();
}else{
console.log("未找到控件");
}
}else{
alert(result.msg);
}
},
error:function(){
alert("服务器未正确响应!");
}
});
};
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化