1 1.前端html代码 2 <div class="layui-form-item"> 3 <label class="layui-form-label">修改头像</label> 4 <div class="layui-input-inline uploadHeadImage"> 5 <div class="layui-upload-drag" id="headImg"> 6 <i class="layui-icon"></i> 7 <p>点击上传图片,或将图片拖拽到此处</p> 8 </div> 9 </div> 10 <div class="layui-input-inline"> 11 <div class="layui-upload-list"> 12 <img class="layui-upload-img headImage" src="" id="demo1"> 13 <p id="demoText"></p> 14 </div> 15 </div> 16 </div> 17 18 19 2.前端js代码 20 <script>layui.use(['form', 'layer','upload',"element"], 21 function() { 22 $ = layui.jquery; 23 var form = layui.form, 24 upload = layui.upload, 25 layer = layui.layer; 26 //拖拽上传 27 var uploadInst = upload.render({ 28 elem: '#headImg' 29 , url: '{:url("uploadImg")}' 30 , size: 500 31 , before: function (obj) { 32 //预读本地文件示例,不支持ie8 33 obj.preview(function (index, file, result) { 34 $('#demo1').attr('src', result); //图片链接(base64) 35 }); 36 } 37 , done: function (res) { 38 console.log(res); 39 //如果上传失败 40 if (res.code > 0) { 41 return layer.msg('上传失败'); 42 } 43 var demoText = $('#demoText'); 44 // demoText.html('<span style="color: #8f8f8f;">上传成功!!!</span>'); 45 $("#imagepath").val(res.image) 46 layer.msg("上传成功") 47 } 48 , error: function () { 49 //演示失败状态,并实现重传 50 var demoText = $('#demoText'); 51 demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>'); 52 demoText.find('.demo-reload').on('click', function () { 53 uploadInst.upload(); 54 }); 55 } 56 }); 57 element.init(); 58 });
1 3.后台php代码 2 // 图片上传 3 public function uploadImg(){ 4 // 上传代码 5 $file = request()->file('file'); 6 // 上传到本地服务器 7 $savename = \think\facade\Filesystem::disk('public')->putFile( 'goods', $file); 8 $data['image'] = $savename; 9 $data['code'] = 0; 10 11 return json($data); 12 }