【腾讯cos对象存储】hyperf腾讯cos上传,腾讯cos sdk使用

4 篇文章 0 订阅
2 篇文章 0 订阅

hyperf2.2文档地址 链接: https://hyperf.wiki/2.2/#/

composer文档 链接: https://wiki.swoole.com/

腾讯cos对象存储文档 链接: https://cloud.tencent.com/document/product/436/12266#composer

hyperf框架文件系统+腾讯cos使用

  1. 文件系统组件集成了 PHP 生态中大名鼎鼎的 League\Flysystem,安装:
composer require hyperf/filesystem
  1. 安装腾讯云对应适配器,结合Flysystem v2.0 版本
composer require "overtrue/flysystem-cos:^4.0"
  1. 安装完成后执行下面,生成config/autoload/file.php文件配置信息
php bin/hyperf.php vendor:publish hyperf/filesystem
  1. 功能代码
<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\Utils\Str;
use App\Constants\ResponseCode;
use Hyperf\HttpServer\Contract\RequestInterface;

class IndexController
{
    public function example(RequestInterface $request,\Hyperf\Filesystem\FilesystemFactory $factory)
    {
        $file = $request->file('file');
        $allowedArr = ['jpg', 'png', 'jpeg', 'gif', 'bmp', 'ico'];
        $ext = strtolower($file->getExtension());
        if (!in_array($ext, $allowedArr)) {
            return [
                'code' => ResponseCode::CODE_ERROR,
                'msg'  => '上传格式不允许',
            ];
        }
        $filePathUrl = 'uploads/' . date('Ymd') . '/' . Str::random(16) . '.' . $ext;
        try {
            $stream = fopen($file->getRealPath(), 'rb');
            $cos = $factory->get('cos');
            $cos->writeStream($filePathUrl, $stream);
            fclose($stream);
            if ($file->getRealPath()) {
                @unlink($file->getRealPath());
            }
            return [
                'code' => ResponseCode::CODE_SUCCESS,
                'msg'  => '上传成功',
                'data' => [
                    'img_origin_url' => config('tx_cos_file_url') . $filePathUrl,
                ]
            ];
        } catch (\Exception $e) {
            return [
                'code' => ResponseCode::CODE_ERROR,
                'msg'  => '上传失败',
                'data' => $e->getMessage()
            ];
        }
    }
}
  1. 重启hyperf,运行
    注意:此时swoole没有安装curl,上传大文件会报这个错误
    在这里插入图片描述

查看swoole已安装的信息,没有curl会显示下图

php --ri swoole

在这里插入图片描述

解决:安装swoole新版本,在加 --enable-swoole-curl 参数编译安装即可,步骤如下:


# 下载swoole对应的版本
wget https://pecl.php.net/get/swoole-4.7.1.tgz
# 解压
tar zxvf swoole-4.7.1.tgz
# cd目录,解压后的 swoole 源码是没有 configure 文件的,这时我们就需要使用 PHP 的 phpize 工具去为 swoole 生成 configure 文件
cd swoole-4.7.1
phpize
# 查找php-config地址
find / -name php-config  # /usr/local/php/bin/php-config
# 创建编译文件,第一个--with是php-config的安装路径,第二个enable是开启功能
./configure --with-php-config=/usr/local/php/bin/php-config  --enable-swoole-curl
# 编译swoole
make clean && make && make instal

此时查看当前扩展,curl-native安装成功,再次运行程序,可以上传大文件啦~

php --ri swoole

在这里插入图片描述
查看当前composer版本:php --ri swoole | grep Version

腾讯cos sdk使用

  1. 安装sdk,composer.json中添加
{
    "require": {
        "qcloud/cos-sdk-v5": ">=2.0"
    }
}
  1. 删除vendor文件,运行composer install ,生成qcloud文件夹
    在这里插入图片描述
  2. 代码编写
/**
     * 上传图片--sdk
     * @RequestMapping(path="upload_img_sdk", methods="post")
     * @param RequestInterface $request
     * @param FileUploadHandler $uploadHandler
     * @return array
     */
    public function upload_img_sdk(RequestInterface $request)
    {
        $file = $request->file('file');
        $allowedArr = ['jpg', 'png', 'jpeg', 'gif', 'bmp', 'ico'];
        $ext = strtolower($file->getExtension());
        if (!in_array($ext, $allowedArr)) {
            return [
                'code' => ResponseCode::CODE_ERROR,
                'msg'  => '上传格式不允许',
            ];
        }
        $filePathUrl = 'uploads/' . date('Ymd') . '/' . Str::random(16) . '.' . $ext;

        // 配置
        $appId = env('TC_APPID', null);
        $bucket = env('TC_COS_BUCKET', null);
        $region = env('TC_COS_REGION', null);
        $secretId = env('TC_SECRET_ID', null);
        $secretKey = env('TC_SECRET_KEY', null);

        $cosClient = new qclient([
            'region' =>  $region,
            'credentials' => array(
                'secretId' => $secretId,
                'secretKey' => $secretKey,
            )
        ]);

        try {
            $result = $cosClient->putObject([
                'Bucket' => $bucket . '-' . $appId, //格式:BucketName-APPID 
                'Key' => $filePathUrl,
                'Body' => fopen($file->getRealPath(), 'rb'),
            ]);

            // 请求成功 
            // 删除本地文件
            if ($file->getRealPath()) {
                @unlink($file->getRealPath());
            }
            // print_r($result);
            return [
                'code' => ResponseCode::CODE_SUCCESS,
                'msg'  => '上传成功',
                'data' => [
                    'img_origin_url' => $result['Location'],
                ]
            ];
        } catch (\Exception $e) {
            return [
                'code' => ResponseCode::CODE_ERROR,
                'msg'  => '上传失败',
                'data' => $e->getMessage()
            ];
        }
    }
  1. 运行
    可能会报这个错误:

PHP Notice: Object of class Swoole\Curl\Handler could not be converted to int in /Users/qiutangfeng/www/cloudmarket-hyperf/vendor/ezimuel/ringphp/src/Client/CurlHandler.php on line 109

Notice: Object of class Swoole\Curl\Handler could not be converted to int in /Users/qiutangfeng/www/cloudmarket-hyperf/vendor/ezimuel/ringphp/src/Client/CurlHandler.php on line 109

解决:升级swoole,开启curl-native,更新步骤如上

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值