php+layui写出图片上传

Ezra
2021-04-22 / 0 评论 / 381 阅读 / 正在检测是否收录...

之前一直用框架加复制前辈的代码来完成图片上传,不清楚图片上传是怎么回事,这次写一个纯php+layui上传图片的例子
文件上传链接
首先前端代码

<div class="layui-form-item">
        <label class="layui-form-label">图片</label>
        <div class="layui-input-block">
            <img id="pre_img" style="height: 30px;" />
            <button class="layui-btn layui-btn-sm" onclick="return false;" id="upload_img">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>
            <input type="hidden" name="img" value="">
        </div>
    </div>
    <script>
    layui.use(['upload','jquery'],function () {
    $ = layui.jquery;
    var upload = layui.upload;
    //执行实例
    var uploadInst = upload.render({
        elem: '#upload_img' //绑定元素
        ,url: '/upload.php' //上传接口
        ,accept:'images'
        ,done: function(res){
            //上传完毕回调
            $('#pre_img').attr('src',res.msg);
            $('input[name="img"]').val(res.msg);
        }
        ,error: function(){
            //请求异常回调
        }
    });
    });
    </script>

当然你可以引入layui在线的样式和js

    <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
    <script src="https://www.layuicdn.com/layui/layui.js"></script>

然后是php代码:

    <?php
    $file = $_FILES["file"];
    if ($file==null) {
        exit(json_encode(array('code'=>1, 'msg'=>'未上传图片')));
    }
    // 获取文件后缀
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    // 判断文件是否合法
    if(!in_array($extension, array("gif","jpeg","jpg","png"))){
        exit(json_encode(array('code'=>1, 'msg'=>'上传图片不合法')));
    }
    $info = move_uploaded_file($file['tmp_name'], "./uploads/".$file['name']); //移动文件到指定目录 建议文件名自己在修改一下
    $img = '/uploads/'.$file['name'];
    exit(json_encode(array('code'=>0, 'msg'=>$img)));
    ?>
0

评论 (0)

取消