HTML基本結構: 選擇圖片 預覽圖: 立即提交 Java... ...
HTML基本結構:
<form class="layui-form" action="" id="feedBackForm">
<div class="layui-form-item">
<!--表單內容-->
</div>
<!--圖片上傳-->
<div class="layui-upload feedback-padding">
<button type="button" class="layui-btn" id="selectImg">選擇圖片</button>
<input type="text" class="layui-hide" name="">
<blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
預覽圖:
<div id="previewImg" class="layui-clear feedback-overflow">
</div>
</blockquote>
</div>
<div class="layui-form-item">
<div class="feedback-block">
<button id="submitBtn" class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
</div>
</div>
</form>
JavaScript基本內容:
1、多圖片上傳、預覽
//多圖片上傳 uploadList = upload.render({ elem: '#selectImg' ,url: "/add.do" ,accept: 'images' ,acceptMime: 'image/*' ,method: 'post' ,multiple: true ,auto: false ,choose: function(obj){ files = obj.pushFile(); //將每次選擇的文件追加到文件隊列 //圖像預覽,如果是多文件,會逐個添加。(不支持ie8/9) obj.preview(function(index, file, result){ var imgBox = document.createElement("div");//預覽圖、刪除預覽圖按鈕容器 var imgDelete = document.createElement("div");//刪除預覽圖按鈕 var imgobj = new Image(); //創建新img對象 imgBox.style.float = 'left'; imgBox.style.position = 'relative'; imgDelete.setAttribute('class',"feedback-delete-btn layui-icon layui-icon-close-fill"); imgDelete.setAttribute ('title','刪除'); imgobj.src = result; //指定數據源 imgobj['layer-src'] = result; imgobj.alt = file.name; imgobj.className = 'layui-upload-img'; imgobj['layer-index'] = index; imgBox.appendChild(imgobj); imgBox.appendChild(imgDelete); imgDelete.onclick = function () { // 為預覽圖的刪除按鈕綁定刪除事件 delete files[index]; //刪除對應的文件 document.getElementById("previewImg").removeChild(imgBox);//從預覽區域移除 uploadList.config.elem.next()[0].value = ''; //清空 input file 值,以免刪除後出現同名文件不可選 } document.getElementById("previewImg").appendChild(imgBox); //添加到預覽區域 //photos 圖片層 layer.photos({//此處目前存在bug 導致單擊後無法在彈層中打開預覽 下麵會講解如何處理 photos: '#previewImg' ,anim: 0 }); }); } });
2、提交
//監聽提交 form.on('submit(demo1)', function(data){ var myForm = document.getElementById("feedBackForm"); var formData = new FormData(myForm); //迴圈 files(第一步choose回調中儲存的對象) 逐條插入到formData for (var i in files) { formData.append("files",files[i]);//此處的files為上傳介面參數名 } $.ajax({ url: "/add.do", type: "POST", data: formData, async: false, contentType: false, processData: false, error: function () { layer.msg('網路超時',{icon:2}); }, success: function (data) { layer.msg('成功',{icon:1}); } }) return false; });
3、步驟一中 layer.photos 重覆調用,導致彈層預覽圖無法正常顯示處理:
修改layer.js源碼 ,點擊事件綁定之前,先用off()進行解綁,避免重覆綁定,如下:
loop || parent.off('click').on('click', options.img, function(){ var othis = $(this), index = othis.attr('layer-index'); layer.photos($.extend(options, { photos: { start: index, data: data, tab: options.tab }, full: options.full }), true); pushData(); })