欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php+layui实现图片上传与预览

程序员文章站 2023-04-08 09:44:35
端代码: php后台: ......

端代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>upload模块快速使用</title>
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
</head>
<body>
    
    <button type="button" class="layui-btn" id="test1">
      <i class="layui-icon">&#xe67c;</i>上传图片
    </button>
    <div class="layui-upload-list">
        <img class="layui-upload-img" width="100px" height="100px" id="demo1">
        <p id="demoText"></p>
    </div>

    <script src="/layui/layui.js"></script>
    <script>

        layui.use('upload', function(){
            var $ = layui.jquery
            ,layer = layui.layer
            ,upload = layui.upload;

            var uploadInst = upload.render({
                elem:'#test1'
                ,url:'/index/upload/upload'
                ,accept:'file'  // 允许上传的文件类型
                ,auto:true // 自动上传
                ,before:function (obj) {
                    // console.log(obj);
                    // 预览
                    obj.preview(function(index,file,result) {
                        // console.log(file.name);    //图片地址
                        // console.log(file.type);    //图片格式
                        // console.log(file.size);    //图片大小
                        // console.log(file);    //图片地址
                        $('#demo1').attr('src',result); //图片链接 base64
                    });
                }
                // 上传成功回调
                ,done:function(res) {
                    // console.log(upload);
                    console.log(res);
                    if (res.code == 0) {
                        layer.msg(res.msg);
                    }else{
                        layer.msg(res.msg);
                    }
                }
                // 上传失败回调
                ,error:function(index,upload) {
                    // 上传失败
                }
            });

        })
    </script>
</body>
</html>

php后台:

public function upload()
    {
        
        $file = request()->file('file');
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info) {
            $data['code'] = 0;
            $data['msg'] = $info->getSaveName();
        }else{
            $data['code'] = 1;
            $data['msg'] = $file->getError();
        }
            return json($data);
    }

 php+layui实现图片上传与预览