1.HTML部分
<div class="layui-upload" style="margin-left:110px;">

<button type="button" class="layui-btn" id="test1">更新头像</button>
<div class="layui-upload-list">
    <img class="layui-upload-img" id="demo1" src="{$data.icon??''}">
    <p id="demoText"></p>
</div>

</div>
注: img的src的值是做的回选,根据需要选择

2.js部分
<script src="/static/layuiadmin/layui/layui.js"></script>

<script>
    layui.use(['upload','form','laydate'], function() { //upload 文件上传
        var form = layui.form
            ,layer = layui.layer
            ,layedit = layui.layedit
            ,laydate = layui.laydate;
        var $ = layui.jquery
            ,upload = layui.upload; //文件上传

        laydate.render({
            elem: '#date1'
        });

        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            , url: '{:url("index/upload")}'
            , before: function (obj) {
                //预读本地文件示例,不支持ie8
                obj.preview(function (index, file, result) {
                    //alert(result);
                    $('#demo1').attr('src', result); //图片链接(base64)
                });
            }
            , done: function (res) {
                //如果上传失败
                if (res.code == 0) {
                    return layer.msg('上传失败');
                }
                //上传成功
                console.log(res);
            }
            , error: function () {
                //演示失败状态,并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });

        //监听提交
        form.on('submit(demo1)', function(data){
            layer.alert(JSON.stringify(data.field), {
                title: '最终的提交信息'
            })
            return false;
        });

    });

</script>

3.PHP部分
/**

 * 文件上传
 */
public function upload(Request $request){
    $file = request()->file('file');
    // 移动到框架应用根目录/public/uploads/ 目录下
    $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
    $reubfo = array();  //定义一个返回的数组
    if($info){
        $reubfo['code']= 1;
        $reubfo['savename'] = "/upload/".$info->getSaveName(); 
    }else{
        // 上传失败获取错误信息
        $reubfo['code']= 0;
        $reubfo['err'] = $file->getError();
    }
    return $reubfo;

}

注:$reubfo['savename'] 可以将这部分存在数据库

上传成功就是这样的,自己马克一下.

ps:请注意layui的版本

转自 : CSDN

标签: layui

添加新评论