thinkphp使用ajax图集上传
1.form表单
<div class="layui-form-item" id="pics"> <div class="layui-form-label">相册图集</div> <div class="layui-input-block" style="width: 70%;"> <div class="layui-upload"> <button type="button" class="layui-btn layui-btn-primary pull-left" id="slide-pc">选择多图</button> <div class="pic-more"> <ul class="pic-more-upload-list" id="slide-pc-priview"> </ul> </div> </div> </div> </div>
2.ajax代码
<script> //图集上传 layui.use('upload', function(){ var $ = layui.jquery; var upload = layui.upload; upload.render({ elem: '#slide-pc', url: "{:url('/seller_Goods/upload')}", size: 500, exts: 'jpg|png|jpeg', multiple: true, before: function(obj) { layer.msg('图片上传中...', { icon: 16, shade: 0.01, time: 0 }) }, done: function(res) { layer.close(layer.msg());//关闭上传提示窗口 if(res.status == 0) { return layer.msg(res.message); } $('#slide-pc-priview').append('<li class="item_img" style="width: 90px;float: left;margin-right: 5px;"><div class="operate"><i class="toleft layui-icon"></i><i class="toright layui-icon"></i><i class="close layui-icon"></i></div><img src="/upload/store_goods/' + res.filepath + '" class="img" ><input type="hidden" id="pc_src" name="pc_src[]" value="' + res.filepath + '" /></li>'); } }); }); //点击多图上传的X,删除当前的图片 $("body").on("click",".close",function(){ var imgurl = $(this).parent().siblings("input[type='hidden']").val(); if(!imgurl){ layer.msg('请先上传图片!', {icon: 2}); return false; } $.ajax({ type:"post", dataType:"json", data:{imgurl:imgurl}, url:"{:url('/seller_Goods/delimg')}", success:function(data){ if(data==1){ layer.msg('撤销成功!', {icon: 1}); }else{ layer.msg('撤销失败!', {icon: 2}); } } }); $(this).closest("li").remove(); }); //多图上传点击<>左右移动图片 $("body").on("click",".pic-more ul li .toleft",function(){ var li_index=$(this).closest("li").index(); if(li_index>=1){ $(this).closest("li").insertBefore($(this).closest("ul").find("li").eq(Number(li_index)-1)); } }); $("body").on("click",".pic-more ul li .toright",function(){ var li_index=$(this).closest("li").index(); $(this).closest("li").insertAfter($(this).closest("ul").find("li").eq(Number(li_index)+1)); }); </script>
3.控制器
//通用多图上传接口 public function upload() { if($this->request->isPost()){ $res['code']=1; $res['msg'] = '上传成功!'; $file = $this->request->file('file'); $info = $file->move('./upload/store_goods/'); if($info){ $res['name'] = $info->getFilename(); $res['filepath'] = '/'.str_replace('\\','/',$info->getSaveName()); }else{ $res['code'] = 0; $res['msg'] = '上传失败!'.$file->getError(); } return $res; } } //多图删除头像 public function delimg(){ $imgurl=input('imgurl'); $imgurl='./upload/store_goods'. $imgurl; $res=unlink($imgurl); if($res){ echo 1; //删除文件成功 }else{ echo 2;//删除文件失败 } }
4.图集新建数据表保存
//添加商品图集 $attr_src = isset($data['pc_src']) ? $data['pc_src'] : ""; if(!empty($attr_src)){ $src = array(); foreach ($attr_src as $k => $v) { $goods_gallery = array( 'goods_id' => $goods_id, 'goods_gallery_1' => $k, //排序 'goods_gallery_2' => $v, //地址 ); db('goods_gallery')->insert($goods_gallery); } }