23、Hyperf 3 快速使用 - Hyperf 3 上传文件 or 图片到腾讯云

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 931

时间: 2023-04-25 15:19:23

hi,我是温新,一名 PHPer

Hypref 版本:Hyperf 3.0

学习目标:掌握上传文件 or 图片到腾讯云

本篇文章学习的是将文件上传到阿里云。在此之前需要准备好阿里云的对象存储空间。

准备工作

第一步:安装组件

composer require hyperf/filesystem
composer require "overtrue/flysystem-cos:^5.0"

第二步:生成配置文件

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

该命令会在 config/autoload 目录下生成 file.php 文件,其中关于七牛云的配置如下:

<?php

'cos' => [
    'driver' => \Hyperf\Filesystem\Adapter\CosAdapterFactory::class,
    'region' => env('COS_REGION'),
    'app_id' => env('COS_APPID'),
    'secret_id' => env('COS_SECRET_ID'),
    'secret_key' => env('COS_SECRET_KEY'),
    // 可选,如果 bucket 为私有访问请打开此项
//             'signed_url' => false,
    'bucket' => env('COS_BUCKET'),
    'read_from_cdn' => false,
    // 'timeout' => 60,
    // 'connect_timeout' => 60,
    // 'cdn' => '',
     'scheme' => 'https',
    'domain'=>'访问图片的域名', // 不加 http/https
],

第三步:.env 文件中填写配置

// .env
COS_REGION=ap-guangzhou
COS_APPID=腾讯云账号 APPID
COS_SECRET_ID=腾讯云 KEY
COS_SECRET_KEY=腾讯云 SECRET
COS_BUCKET=bucket

第四步:创建控制器

<?php

namespace App\Controller\Test;

use Hyperf\HttpServer\Annotation\Controller;

#[Controller]
class TxUploadController
{
}

上传图片到腾讯云

方法一:通过实例方式上传

上传图片案例

<?php

//App\Controller\Test\TxUploadController.php

use Hyperf\Contract\ConfigInterface;    
    
use Hyperf\Filesystem\FilesystemFactory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\Utils\ApplicationContext;
use League\Flysystem\Config;

#[PostMapping('/tx/store')]
public function store()
{
    $path = 'a.jpg';

    $container = ApplicationContext::getContainer();
    $options = $container->get(ConfigInterface::class)->get('file');

    $filesystemFactory = $container->get(FilesystemFactory::class);
    $adapter = $filesystemFactory->getAdapter($options, 'cos');

    if ($adapter->fileExists('hyperf/' . $path)) {
        return 'exists';
    }

    $adapter->writeStream('hyperf/' . $path, fopen($path, 'r'), new Config());
    return 'succ';
}

方法二:使用依赖注入

1、通过 Hyperf\Filesystem\FilesystemFactory; 实现

第一步:控制器

<?php

namespace App\Controller\Test;

use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\ContainerInterface;
use Hyperf\Filesystem\FilesystemFactory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\View\RenderInterface;
use League\Flysystem\Config;
use League\Flysystem\FilesystemAdapter;

#[Controller]
class TxUploadController
{
    protected FilesystemAdapter $adapter;

    public function __construct(protected ContainerInterface $container, $adapterName = 'cos')
    {
        $this->adapter = $this->getAdapter($adapterName);
    }

    public function getAdapter($adapterName)
    {
        $options = $this->container->get(ConfigInterface::class)->get('file');
        $filesystemFactory = $this->container->get(FilesystemFactory::class);

        return $filesystemFactory->getAdapter($options, $adapterName);
    }
    #[GetMapping('/tx/create')]
    public function create(RenderInterface $render)
    {
        return $render->render('txoss.create');
    }

    #[PostMapping('/tx/store')]
    public function store(RequestInterface $request)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $newFilename = 'hyperf/' . date('YmdHis') . uniqid() . '.' . $file->getExtension();
            $stream = fopen($file->getRealPath(), 'r');
            $this->adapter->writeStream($newFilename, $stream, new Config());

            return '图片上传成功';
        }
    }
}

第二步:视图文件

<!-- storage/txoss/create.blade.php -->
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>COS</title>
</head>
<body>
    <form method="post" action="/tx/store" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="上传图片">
    </form>
</body>
</html>

2、使用 \League\Flysystem\Filesystem $filesystem 对象实现

这一步只修改修改控制器对的方法即可,如下:

<?php

namespace App\Controller\Test;

use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\ContainerInterface;
use Hyperf\Filesystem\FilesystemFactory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\View\RenderInterface;
use League\Flysystem\Config;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemAdapter;

#[Controller]
class TxUploadController
{
    protected FilesystemAdapter $adapter;

    protected $filesystem;

    public function __construct(protected ContainerInterface $container, $adapterName = 'cos')
    {
        $this->adapter = $this->getAdapter($adapterName);
        // 改动
        $this->filesystem = new Filesystem($this->adapter);
    }

    public function getAdapter($adapterName)
    {
        $options = $this->container->get(ConfigInterface::class)->get('file');
        $filesystemFactory = $this->container->get(FilesystemFactory::class);

        return $filesystemFactory->getAdapter($options, $adapterName);
    }
    #[GetMapping('/tx/create')]
    public function create(RenderInterface $render)
    {
        return $render->render('txoss.create');
    }

    #[PostMapping('/tx/store')]
    public function store(RequestInterface $request)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $newFilename = 'hyperf/' . date('YmdHis') . uniqid() . '.' . $file->getExtension();
            $stream = fopen($file->getRealPath(), 'r');
            // 改动
            $this->filesystem->writeStream($newFilename, $stream);

            return '图片上传成功';
        }
    }
}
请登录后再评论