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

全屏阅读
  • 基本信息

端代码:

<!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);
    }

image.png

顶一下
(0)
100%
订阅 回复
踩一下
(0)
100%
» 郑重声明:本文由mpxq168发布,所有内容仅代表个人观点。版权归恒富网mpxq168共有,欢迎转载, 但未经作者同意必须保留此段声明,并给出文章连接,否则保留追究法律责任的权利! 如果本文侵犯了您的权益,请留言。

目前有 0 条留言 其中:访客:0 条, 博主:0 条

给我留言

您必须 [ 登录 ] 才能发表留言!