侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Hyperf2.1框架文件上传,实现上传头像功能

swoole  /  管理员 发布于 1年前   1800

今天用hyperf2.1框架实现头像上传功能,看看手册的介绍


文件系统组件集成了 PHP 生态中大名鼎鼎的 League\Flysystem (这也是 Laravel 等诸多知名框架的底层库)。通过合理抽象,程序不必感知存储引擎究竟是本地硬盘还是云服务器,实现解耦。本组件对常用的云存储服务提供了协程化支持。

开始功能开发


安装组件

composer require hyperf/filesystem

生成配置文件

php bin/hyperf.php vendor:publish hyperf/filesystem

就会生成 config/autoload/file.php 文件。在该文件中设置默认驱动,并配置对应驱动的 access key、access secret 等信息就可以使用了。

配置:

    'default' => 'local',
    'storage' => [
        'local' => [
            'driver' => \Hyperf\Filesystem\Adapter\LocalAdapterFactory::class,
            //'root' => __DIR__ . '/../../runtime',
            'root' => __DIR__ . '/../../public/upload',
        ],

所以后面上传的头像就会上传到这个目录下

/hyperf/public/upload


使用

我把功能放在用户信息编辑里面开发


添加路由

//编辑用户信息  上传头像
Router::addRoute(['GET', 'POST', 'HEAD'],'edituser','App\Controller\UserController@edituser');

控制器

/hyperf/app/Controller/UserController.php

    //编辑用户信息  只留上传头像的代码 其他代码忽略了
    public function edituser(RenderInterface $render,RequestInterface $request,\League\Flysystem\Filesystem $filesystem)
    {
        if ($this->request->isMethod('post')) {
            //获取上传的文件
            $file = $this->request->file('face');
            if(isset($file)){
                //资源
                $stream = fopen($file->getRealPath(), 'r+');
                //重命名 拼接上传路径
                $rename = date('Y-m-d').uniqid() .'.'.explode('.',$file->getClientFilename())[1];
                $filesystem->writeStream('face/'.$rename, $stream);
                // Check if a file exists
                if(!$filesystem->has('face/'.$rename)){
                    return array('error' => 0, 'info' => '头像上传失败,请重新上传');
                }
                //把不是默认头像的旧头像删了
                if($this->session->get('user')->face != '/upload/face/mrface.jpg'){
                    // Delete Files
                    $filesystem->delete($this->session->get('user')->face);
                }
                fclose($stream);
                $data['face'] = '/upload/face/'.$rename;
            }
            //入库
            $res = Db::table('user')->where('user_id', $this->session->get('user')->user_id)->update($data);
            if($res){
                //重置session
                $this->session->set('user', Db::table('user')->where('user_id', $this->session->get('user')->user_id)->first());
                return array('error' => 1, 'info' => '编辑成功');
            }else{
                return array('error' => 0, 'info' => '编辑失败或没有变动');
            }
        }
        return $render->render('home/user/edituser',
            [
                'cats'=> $this->cats,
                'session' => $this->session->get('user')
            ]
        );
    }


前端

/hyperf/storage/view/home/user/edituser.blade.php

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="row clearfix">
                <div class="col-md-4 column"></div>
                <div class="col-md-4 column">
                    <h3 style="padding: 5rem;">hyperf {{$tdk['keywords']}}</h3>
                    <form class="form-horizontal" id="myForm" action="/user/edituser" method="post" role="form" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-2 control-label">账号</label>
                            <div class="col-sm-10"><input disabled="disabled" value="{{$session->email}}" class="form-control" id="inputEmail3" /></div>
                        </div>
                        <div class="form-group">
                            <label for="name" class="col-sm-2 control-label">用户</label>
                            <div class="col-sm-10"><input disabled="disabled" value="{{$session->username}}" class="form-control" /><span id="check_user" style="font-size: 8px;color: red;display: none;"></span></div>
                        </div>
                        <div class="form-group">
                            <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
                            <div class="col-sm-10"><input type="password" name="password" value="{{$session->password}}" class="form-control" id="inputPassword3" placeholder="请输入密码" /></div>
                        </div>
                        <div class="form-group">
                            <label for="exampleInputFile" class="col-sm-2 control-label">头像</label>
                            <div class="col-sm-10"><input type="file" name="face" id="exampleInputFile" placeholder="请输入密码"></div>
                            <p class="help-block">&nbsp;&nbsp;&nbsp; 请上传你喜欢的头像,不传则系统默认生成</p>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10"><button type="submit" class="btn btn-default">提交</button></div>
                        </div>
                    </form>
                </div>
                <div class="col-md-4 column"></div>
            </div>
        </div>
    </div>
<script type="text/javascript" src="/js/jquery.form.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        // bind form using ajaxForm
        $('#myForm').ajaxForm({
            dataType:  'json',
            // success:   processJson
            success: function(data){ console.log(data);
                if (data.error == 1) {
                    alert(data.info);
                    //location.reload();
                    location.href = "/user/center";
                }else{
                    $("#check_user").html(data.info);
                    $("#check_user").css("display","block");
                };
            }
        });
    });
</script>


完事看看效果

1.添加照片  点击上传

1.png


2.png


3.png


5.png



完





  • 上一条:
    Hyperf2.1框架基于websocket协议实现群聊,聊天功能
    下一条:
    你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在hyperf框架中使用基于protobuf的RPC生成器实现rpc服务(0个评论)
    • hyperf + 京东联盟sdk实现简单商品列表转链跳转购买商品功能示例(0个评论)
    • Hyperf 3.0版本发布(0个评论)
    • hyperf2.2框架中添加Cache代理类的流程步骤及使用案例(0个评论)
    • hyperf2.1框架使用Dockerfile部署流程步骤(0个评论)
    • 近期文章
    • 在laravel框架中的5个HTTP客户端技巧分享(0个评论)
    • 在go语言中使用FFmpeg库实现PCM音频文件编码为mp3格式文件流程步骤(0个评论)
    • gopacket免安装Pcap实现驱动层流量抓包流程步骤(0个评论)
    • 在laravel项目中实现密码强度验证功能推荐扩展包:password-strength(0个评论)
    • 在go语言中用filepath.Match()函数以通配符模式匹配字符串示例(0个评论)
    • Laravel Response Classes 响应类使用优化浅析(0个评论)
    • mysql中sql_mode的各模式浅析(0个评论)
    • 百度文心一言今天发布,个人第一批内测体验记录,不好别打我(0个评论)
    • 嘿加密世界让我们谈谈在共识中将中本聪主流化(0个评论)
    • 在go语言中寻找两个切片或数组中的相同元素/共同点/交集并集示例代码(0个评论)
    • 近期评论
    • 博主 在

      2023年国务院办公厅春节放假通知:1月21日起休7天中评论 @ xiaoB 你只管努力,剩下的叫给天意;天若有情天亦老,..
    • xiaoB 在

      2023年国务院办公厅春节放假通知:1月21日起休7天中评论 会不会春节放假后又阳一次?..
    • BUG4 在

      你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事中评论 不是吧?..
    • 博主 在

      go语言+beego框架中获取get,post请求的所有参数中评论 @ t1  直接在router.go文件中配就ok..
    • Jade 在

      如何在MySQL查询中获得当月记录中评论 Dear zongscan.com team, We can skyroc..
    • 2017-09
    • 2020-03
    • 2020-06
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-11
    • 2022-03
    • 2022-05
    • 2023-01
    • 2023-02
    • 2023-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客