先new 一个fileReader。
主要方法
// try sending var reader = new FileReader(); reader.onloadstart = function() { console.log("onloadstart"); } reader.onprogress = function(p) { console.log("onprogress"); } reader.onload = function() { console.log("load complete"); } reader.onloadend = function() { }form表单<input type="file" id=“imagemain”> 选择文件时
document.getElementById('imagemain').addEventListener('change',function (event){});点击按钮添加图片
<form method="post" enctype="multipart/form-data"> <div id="formitem-bigpic"> <div class="bigpic bigpic-add"> 添加<br>图片 <input type="file" id="imagemain" name="image"> </div> </div> </form>
利用formData提交表单数据
var formData = new FormData(); formData.append('key1','value1'); formData.append('key2','value2');
formData.get('key1'); //返回value1 formData.has('123'); // Returns false formData.delete('key1');//删除
var data = new FormData(); data.append('key1',21321); console.log(data); for(let i of data.entries()) { console.log(i[0]+ ','+ i[1]); } console.log('-------delete -------'); data.delete('key1'); for(let i of data.entries()) { console.log(i[0]+ ','+ i[1]); } console.log('-----delete------'); data.set('key1',43232); // data.append('key1',21321); data.append('key1','213opop'); console.log(data.get('key1')); //获得 首先设置的值 console.log(data.getAll('key1'));
//图片添加 fileApi var handleFileSelect = (function () { var readerInstance; function inInt(args) { var args = args || {},fileJson = {},xhr = new XMLHttpRequest(),reader = new FileReader(); this.fatherEle = args.fatherEle; this.sonClz = args.sonClz; this.Index = args.Index; this.maxSize = args.maxSize; this.inputImage = args.inputImage; this.inputItem = args.inputItem; this.addMethod = args.addMethod; this.delMethod = args.delMethod; function loadFile(evt,callback) { var file = evt.target.files[0]; //取消时 if (file === undefined) { return false; } if (!file.type.match('image.*')) { errMsgBox('图片格式请选择为png,jpg,jpeg等'); return false; } if ((file.size / 1024) > maxSize) { errMsgBox('图片大小不能超过' + (maxSize / 1024).toFixed(2) + 'M'); return false; } //是否存在 /* var boo = isExists(file); if(boo) return false;*/ //开始选择 reader.onloadstart = (function () { loadStart(); fileOnload(file,callback); })(file,callback); }; //load complete function fileOnload(file,callback) { reader.onload = (function () { return function (e) { createEle(e.target.result,file.name,file.type); } })(file); reader.readAsDataURL(file); //上传 返回ajaxEnd var endFunc = ajaxPost(file,ajaxEnd); //上传结束 成功 或失败 return endFunc(loadEnd,callback); }; function ajaxPost(file,fn) { var oData = formDataFunc(); //oData.append('fileImage',file); oData.append('fileImage',file); xhr.open("POST",addMethod,true); var endFn = fn(); xhr.send(oData); return endFn; }; function ajaxDel(id,fn) { xhr.open('POST',delMethod,true); var oData = formDataFunc(); oData.append('id',id); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { inputImage.value = ''; fn.call(this,JSON.parse(xhr.responseText)); }; } }; xhr.send(oData); }; //上传结果返回 function ajaxEnd() { return function (fn,callback) { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { inputImage.value = ''; fn.call(this,JSON.parse(xhr.responseText),callback); } }; }; }; // formdata 数据添加 function formDataFunc() { var oData = new FormData(); for (var i = 0,j; j = inputItem[i++];) { oData.append(j.name,j.value); } return oData; }; //显示图片上传div function loadStart() { var head = document.getElementsByClassName('m-head')[0]; var child = document.getElementById('sure-disabled'); if (child === null) { child = document.createElement('div'); child.setAttribute('class','sure-disabled'); child.setAttribute('id','sure-disabled'); head.appendChild(child); } else { child.style.display = 'block'; } inputImage.setAttribute('disabled','disabled') }; //上传结束 function loadEnd(data,callback) { var sure = document.getElementById('sure-disabled'); sure.style.display = 'none'; if (data.status != 0) { var child = fatherEle.getElementsByClassName('bigpic'); var idx = child.length - 2; fatherEle.removeChild(child[idx]); } var clear = setTimeout(function(){ inputImage.removeAttribute('disabled'); clearTimeout(clear); clear = null; },200) callback.call(this,data); }; //判断图片是否已经添加 function isExists(fileObj) { var fileName = fileObj.name; //不为空 未添加过 if (Object.getOwnPropertyNames(fileJson).length === 0) { fileJson[fileName] = file.type; return false; } if (fileJson[fileName] != fileObj.type) { fileJson[fileName] = file.type; return false; } else { alert('该图片已经上传'); return true; } }; // 创建并添加元素 function createEle(srcStr,fileName,fileType) { var sonEle = fatherEle.getElementsByClassName(sonClz),sonLen = sonEle.length,tagEle = sonEle[sonLen - Index],div = document.createElement('div'); div.setAttribute('class',sonClz); div.innerHTML = '<img src="' + srcStr + '"/><em class="delete_pic" data-msg="' + fileName + ':' + fileType + '"></em>'; fatherEle.insertBefore(div,tagEle); }; return { //添加图片 fn 定义服务器返回 loadFileFunc: function (e,callback) { loadFile(e,callback); },//删除图片 delFileFunc: function (param,fn) { ajaxDel(param,fn) },//清空 已经添加的图片信息 cleanFile: function () { fileJson = {}; },//删除一张 图片信息 cleanOneFile: function (data) { var dataAry = data.split(':'),fileName = dataAry[0],flieType = dataAry[1],tmpJson = {}; for (var i in fileJson) { if (!(i == fileName && flieType == fileJson[i])) { tmpJson[i] = fileJson[i]; } } fileJson = tmpJson; },//添加Form 信息 inputItem 固定参数补充 addInputItem: function (ary) { inputItem = inputItem.concat(ary); },//点击确定后 添加图片 showLoad: function () { var clz = fatherEle.getAttribute('class'); if (clz.indexOf('formitem-top') < 0) { var clz = clz + ' formitem-top'; fatherEle.setAttribute('class',clz); } } }; }; return { getReaderInstance: function (args) { return readerInstance; } }; })();
var flieFunc = handleFileSelect.getReaderInstance({ inputImage: document.getElementById('imagemain'),//inputfile 按钮 inputItem: [document.getElementById('comm')],//固定参数 fatherEle: document.getElementById('formitem-bigpic'),//容器 addMethod: addMethod,//添加 图片请求路径 delMethod: delMethod,//删除 图片请求路径 sonClz: 'bigpic',Index: 1,//追加图片的位置 maxSize: 10300// 图片最大 大小限制 });
document.getElementById('imagemain').addEventListener('change',function (event) { flieFunc.addInputItem([document.getElementById('comment_id')]); flieFunc.loadFileFunc(event,function (rtn) { console.log(rtn + ' 上传成功后返回数据'); }); },false);