曹え 5811 发布于:2021-11-16 08:54:37
使用layui 上传组件
第一步
<button type="button" class="layui-btn" id="test1"> <i class="layui-icon"></i>上传图片 </button> <input type="hidden" value="" id="inpimg" name="pics">
第二步
<script> layui.use(['form', 'upload','laytpl'], function(){ var form = layui.form ,layer = layui.layer ,laytpl = layui.laytpl ,upload = layui.upload; var uploadInst = upload.render({ elem: '#test1' //绑定元素 ,url: 'pro_db.php?m=upimg' //上传接口 ,done: function(res){ console.log(res) //上传完毕回调 if(res.code==200){ $('#inpimg').val(res.img) console.log(str) } _layer.msg(res.msg) } ,error: function(){ //请求异常回调 } }); }); </script>
php 接口
if (!$_FILES['file']['error']){ if ($_FILES['file']['type'] == 'image/jpeg' || $_FILES['file']['type'] == 'image/png'){ if ($_FILES['file']['size']<200000){ //文件传到文件夹中,可以拼接时间戳,用户名等防止文件名重复 $file_name = "upload/".mt_rand(100,9999).$_FILES['file']['name']; if (!file_exists($file_name)){ move_uploaded_file($_FILES['file']['tmp_name'],$file_name); // $filename=iconv("UTF-8","",$file_name); $img = $file_name; exit(json_encode(array('code'=>200,'msg'=>'上传成功', 'img'=>$img))); }else{ exit(json_encode(array('code'=>0,'msg'=>'文件已经存在'))); } }else{ exit(json_encode(array('code'=>0,'msg'=>'文件太大了,不能超过2M'))); } }else{ exit(json_encode(array('code'=>0,'msg'=>'文件格式错误,只能上传jpg和png格式图片'))); var_dump($_FILES); } }else{ exit(json_encode(array('code'=>0,'msg'=>'上传失败'))); }
登录后可以留言提问!
微信扫码登录