# 首先执行
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;
}
}
可能会报这个错误
解决方法