我这个图片上传使用的 layui自带的文件上传插件
上传前效果图:
上传后效果图:
效果还是蛮漂亮的对吧。。
直接上代码不啰嗦:
HTML代码:
1 <div class="layui-form-item"> 2 <label class="layui-form-label"> 3 文章封面 4 </label> 5 <button type="button" class="layui-btn" id="news_img_button" >上传图片</button> 6 <input type="hidden" value="" id="news_pic" name="news_pic" required="" lay-verify="news_img" autocomplete="off" class="layui-input"> 7 <div class="layui-upload-list"> 8 <label class="layui-form-label"> 9 </label> 10 <img class="layui-upload-img" id="newsimg" style=" 200px;height: 140px;margin: 0 10px 10px 0;" src="" onerror="this.src='/admin/images/no_img.png'"> 11 <p id="newsimg_text"></p> 12 </div> 13 </div>
JS代码
1 <script> 2 layui.use('upload', function(){ 3 var $ = layui.jquery 4 ,upload = layui.upload; 5 6 //普通图片上传 7 var uploadInst = upload.render({ 8 elem: '#news_img_button' 9 ,url: '/admin/news/uploadImg' 10 ,before: function(obj){ 11 //预读本地文件示例,不支持ie8 12 obj.preview(function(index, file, result) 13 { 14 $('#newsimg').attr('src', result); //图片链接(base64) 15 }); 16 } 17 ,done: function(res){ 18 19 //如果上传失败 20 if(res.status == 'SUCCESS') 21 { 22 $("#news_pic").attr('value',res.filename) 23 } 24 if(res.status== 'FAIL') 25 { 26 //$("#newsimg_text").html(res.msg); 27 layer.msg(res.msg); 28 } 29 //上传成功 30 } 31 32 }); 33 }); 34 </script>
控制器代码:
1 //控制器代码 2 public function uploadImg() 3 { 4 // 获取表单上传文件 例如上传了001.jpg 5 $file = request()->file('file'); 6 $fiels = request()->file(); 7 // 上传到本地服务器 8 try { 9 validate(['image'=>'fileSize:5120|fileExt:jpg,png,gif,jpeg,bmp|fileMime:image/jpeg,image/gif,image/png,image/bmp'])->check($fiels); 10 11 $savename = \think\facade\Filesystem::disk('public')->putFile( 'news', $file); 12 13 return json(array('status'=>'SUCCESS','msg'=>"上传成功",'filename'=>"/uploads/".$savename)); 14 15 } catch (\think\exception\ValidateException $e) { 16 17 return json(array('status'=>'FAIL','msg'=>"上传失败".$e->getMessage())); 18 } 19 }