js+ajax 上传多图片,并删除
<div class="df mb20"> <input type="text" readonly placeholder="请选择图片" class="form-control col-sm-6"> <input type="text" style="width: 100px;" readonly value="请选择图片" class="btn btn-default" > <input type="file" id="picture" name="cover" multiple class="btn btn-default" style="width: 100px;height:35px;line-height:85px;position: absolute;right: 15px;z-index: 1;background: transparent;" /> <input type="hidden" name="s_imgpath[]" id="s_imgpath" > </div> <div id="previewImg" style="display: flex;justify-content: flex-start;align-items: flex-start;"></div> <style> #previewImg div{margin-right: 10px;margin-bottom: 10px;} .hide{display: none !important;} #previewImg div{position: relative;} .show{width: 20px;height: 20px;background: #0275D8;border-radius: 50%;position:absolute;top: 0;right: 0;z-index: 99} .show::after{content: 'x';color: #fff;width:20px;text-align: center;position: absolute;top:0;left: 0;right: 0;bottom: 0;margin:0 auto;} </style>
// 多张图片 var arr=[] $('#picture').on('change', function(){ var imgFiles = $(this)[0].files console.log("多张图片",imgFiles) var formData = new FormData(); for (i=0;i<imgFiles.length;i++){ filePath = imgFiles[i].name; fileFormat = filePath.split('.')[1].toLowerCase() if( !fileFormat.match(/png|jpg|jpeg/) ) { alert('上传错误,文件格式必须为:png/jpg/jpeg') return } formData.append('upfile', $(this)[0].files[i]); //添加图片信息的参数 var preview = document.getElementById("previewImg") var div = document.createElement('div') var a = document.createElement('a') var img = document.createElement('img') $.ajax({ url: "/upload", type: "post", dataType: "json", cache: false, mimeType: "multipart/form-data", data: formData, processData: false,// 不处理数据 contentType: false, // 不设置内容类型 async:false, success:function (result){ arr[i]=result img.width = 150 img.src = arr[i] preview.appendChild(div) div.appendChild(a) div.appendChild(img) $('#s_imgpath').val(arr) //这儿 把我返回的值, 插入到那个数组里面 s_imgpath[] } }); } }) //控制"按钮"显示与隐藏 $("#previewImg").off("mouseenter","div").on("mouseenter","div",function(){ var that=this; var dom=$(that).children("a"); dom.removeClass("hide"); dom.addClass("show"); //为点击事件解绑,防止重复执行 dom.off("click"); dom.on("click",function(){ //删除当前图片 dom.parent().remove(); var imgsrc = dom.parent().children("img")[0].src //当前图片src arr.removeByValue(imgsrc); //从数组中移除当前图片 $('#s_imgpath').val(arr) //给input重新赋值 }); }).off("mouseleave","div").on("mouseleave","div",function(){ var that=this; $(that).children("a").addClass("hide"); }) Array.prototype.removeByValue = function(val) { //删除数组中元素 for(var i=0; i<this.length; i++) { if(this[i] == val) { this.splice(i, 1); break; } } }