thinkPHP+layui头像上传

时间:2024-05-23 21:25:54

基于thinkPHP的文件上传+layui实现头像上传功能:

HTML代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="__PUBLIC__/layui/css/layui.css">
</head>
<body>
<form class="layui-form" enctype="multipart/form-data" method="POST" action="{:U('img/doedit')}">
    <input type="hidden" name="id" value="{$my['id']}">
    <div class="layui-form-item">
        <label class="layui-form-label"></label>
        <if condition="!$my['img']">
            <img src="__PUBLIC__/img/tx1.jpg"
                 style="width: 100px;height: 100px;background-size: 100% 100%;border-radius: 50%"
                 class="layui-upload-img tx">
            <else/>
            <img src="__ROOT__/Uploads/{$my.img}"
                 style="width: 100px;height: 100px;background-size: 100% 100%;border-radius: 50%"
                 class="layui-upload-img tx">
        </if>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">修改头像</label>
        <input class="layui-input layui-input-inline" type="file" name="img" id="pic">
    </div>

    <div class="btn-left">
        <input class="layui-btn" type="submit" value="提交">
    </div>
</form>
<script>
    //JavaScript代码区域
    layui.use(['element', 'form', 'layer'], function () {
        var element = layui.element;
        var form = layui.form;
        form.render();
    });
</script>
</body>
</html>

controller代码:

<?php

namespace Home\Controller;

use Think\Controller;

class ImgController extends Controller
{
    public function edit()
    {
        $my = M('img')->where("id=1")->find();
//        dump($my);
        $this->assign('my', $my);
        $this->display();
    }

    public function doedit()
    {
        $user = M('img');
        $data = $user->create();
        if ($_FILES['img']['tmp_name'] != '') {
            $upload = new \Think\Upload();
            $upload->maxSize = 3145728;
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
            $upload->rootPath = './Uploads/';
            $upload->savePath = '';
            $info = $upload->uploadOne($_FILES['img']);
            if (!$info) {
                $this->error($upload->getError());
            } else {
                $data['img'] = $info['savepath'] . $info['savename'];
            }
        }
        $result = $user->save($data);
//        dump($result);
//  !!!!!!save()方法执行失败返回false,无修改操作返回0,
//在判断是否更新成功时需要用恒等判断而不是根据返回值是否存在判断。
        if ($result !== false) {
            $this->success('修改成功', U('img/edit'));
        } else {
            $this->error('修改失败');
        }
    }
}

框架结构:

thinkPHP+layui头像上传 

 数据库设计:

thinkPHP+layui头像上传

demo下载地址: https://download.****.net/download/weixin_42545184/10891607