阿里云oss上传

# 首先执行
composer require hyperf/filesystem
# 使用阿里云 OSS 适配器时执行
composer require xxtime/flysystem-aliyun-oss
安装完成后,执行
php bin/hyperf.php vendor:publish hyperf/filesystem
<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use Hyperf\Di\Annotation\Inject;
use Hyperf\Filesystem\FilesystemFactory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use League\Flysystem\Filesystem;
use Xxtime\Flysystem\Aliyun\OssAdapter;

/**
 * Class IndexController
 *
 * @package App\Controller
 * @Controller()
 */
class IndexController extends AbstractController
{

    /**
     * @Inject()
     * @var RequestInterface
     */
    protected $request;


    /**
     * @return array|void
     * @PostMapping(path="/index/upload")
     */
    public function upload(
        FilesystemFactory $factory,
        Filesystem $filesystem
    ) {
        $file = $this->request->file('upload');
        $file_stream = fopen($file->getRealPath(), 'r+');
        $file_path = 'uploads/'.time().'.'.$file->getExtension();
        $filesystem->writeStream(
            $file_path,
            $file_stream
        );
        fclose($file_stream);
        $file_content = file_get_contents('runtime/'.$file_path);

        $oss = $factory->get('oss');
        $config = $oss->getConfig();
        // 配置
        $adapter = new OssAdapter([
            'accessId' => $config->get('accessId'),
            'accessSecret' => $config->get('accessSecret'),
            'bucket' => $config->get('bucket'),
            'endpoint' => $config->get('endpoint'),
            'timeout' => 3600,
            'connectTimeout' => 10,
        ]);
        $filesystem = new Filesystem($adapter);

        // 设置属性
        // 如设置了Content-Type,则可以不指定路径的后缀 (即$filePath可以不包含.jpg等后缀名)
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $mime_type = $finfo->buffer($file_content);
        $config = [
            "Content-Type" => $mime_type,
        ];
        $filePath = "uploadPathTest/".time().'.'.$file->getExtension();

        // 上传
        if (!$filesystem->write($filePath, $file_content, $config)) {
            exit("failed to upload");
        }

        // 获取信息
        $raw = $adapter->supports->getFlashData();
        $url = $raw['info']['url'];

        return $url;
    }
}

可能会报这个错误

解决方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值