22、Hyperf 3 快速使用 - Hyperf 3 上传文件 or 图片到阿里云

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 565

时间: 2023-04-25 15:17:43

hi,我是温新,一名 PHPer

Hypref 版本:Hyperf 3.0

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

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

准备工作

第一步:安装组件

composer require hyperf/filesystem
composer require hyperf/flysystem-oss

第二步:生成配置文件

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

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

'oss' => [
    'driver' => \Hyperf\Filesystem\Adapter\AliyunOssAdapterFactory::class,
    'accessId' => env('OSS_ACCESS_ID'),
    'accessSecret' => env('OSS_ACCESS_SECRET'),
    'bucket' => env('OSS_BUCKET'),
    'endpoint' => env('OSS_ENDPOINT'),
    // 'timeout' => 3600,
    // 'connectTimeout' => 10,
    // 'isCName' => false,
    // 'token' => null,
    // 'proxy' => null,
],

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

OSS_ACCESS_ID=你的阿里云 key
OSS_ACCESS_SECRET=你的阿里云 secret
OSS_BUCKET=你的阿里云 bucket
OSS_ENDPOINT=你的阿里云 endpoint

第四步:创建控制器

<?php

namespace App\Controller\Test;

use Hyperf\HttpServer\Annotation\Controller;

#[Controller]
class OssUploadController
{
}

上传图片到阿里云

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

通过案例快速体验上传图片到阿里云

#[PostMapping('/oss/store')]
public function store()
{
    // 实例化容器对象
    $container         = ApplicationContext::getContainer();
    // 实例 Config 配置对象,并获取 file.php 配置文件内容
    $options           = $container->get(ConfigInterface::class)->get('file');
    // 获取文件工厂实例
    $filesystemFactory = $container->get(FilesystemFactory::class);
    // 获取阿里云实例对象
    $adapter           = $filesystemFactory->getAdapter($options, 'oss');

    $path = 'a.jpg';
    if ($adapter->fileExists('hyperf/' . $path)) {
        // 文件已上传则返回文件大小
        return $adapter->fileSize('hyperf/' . $path)->fileSize();
    }

    // 上传图片
    $adapter->writeStream($path, fopen($path, 'r'), new Config());
    // 返回图片大小
    return $adapter->fileSize('hyperf/' . $path)->fileSize();
}

方法二:使用依赖注入

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\Utils\ApplicationContext;
use Hyperf\View\RenderInterface;
use League\Flysystem\Config;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemAdapter;


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

    public function __construct(protected ContainerInterface $container, $adapterName = 'oss')
    {
        $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('/oss/create')]
    public function create(RenderInterface $render)
    {
        return $render->render('alioss.create');
    }

    #[PostMapping('/oss/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 $this->adapter->fileSize($newFilename)->fileSize();
        }
    }
}

第二步:视图文件

<!-- storage/view/oss/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>Hyperf 3 上传图片</title>
</head>
<body>
<form action="/oss/store" method="post" 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\Utils\ApplicationContext;
use Hyperf\View\RenderInterface;
use League\Flysystem\Config;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemAdapter;


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

    // 改动
    protected $filesystem;

    public function __construct(protected ContainerInterface $container, $adapterName = 'oss')
    {
        $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('/oss/create')]
    public function create(RenderInterface $render)
    {
        return $render->render('alioss.create');
    }

    #[PostMapping('/oss/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 $this->filesystem->fileSize($newFilename);
        }
    }
}

文件上云是一个常用功能。

请登录后再评论