本文目录导读:

在ThinkPHP框架中,文件系统驱动(Filesystem)主要用于处理文件的上传、下载、读写等操作,ThinkPHP 6.0+ 版本对文件系统进行了重构,使用League\Flysystem作为底层驱动。
配置文件
配置文件位于 config/filesystem.php:
<?php
return [
// 默认磁盘
'default' => env('filesystem.driver', 'local'),
// 磁盘列表
'disks' => [
// 本地磁盘
'local' => [
'type' => 'local',
'root' => app()->getRuntimePath() . 'storage',
],
// 公共磁盘
'public' => [
'type' => 'local',
'root' => app()->getRootPath() . 'public/storage',
'url' => '/storage',
'visibility' => 'public',
],
// 私有磁盘
'private' => [
'type' => 'local',
'root' => app()->getRuntimePath() . 'private',
'visibility' => 'private',
],
// 阿里云OSS
'oss' => [
'type' => 'aliyun',
'accessId' => env('aliyun.accessId', ''),
'accessSecret' => env('aliyun.accessSecret', ''),
'bucket' => env('aliyun.bucket', ''),
'endpoint' => env('aliyun.endpoint', ''),
'url' => env('aliyun.url', ''),
'prefix' => '',
],
// 腾讯云COS
'cos' => [
'type' => 'cos',
'secretId' => env('cos.secretId', ''),
'secretKey' => env('cos.secretKey', ''),
'bucket' => env('cos.bucket', ''),
'region' => env('cos.region', ''),
'url' => env('cos.url', ''),
'prefix' => '',
],
// 七牛云
'qiniu' => [
'type' => 'qiniu',
'accessKey' => env('qiniu.accessKey', ''),
'secretKey' => env('qiniu.secretKey', ''),
'bucket' => env('qiniu.bucket', ''),
'domain' => env('qiniu.domain', ''),
'prefix' => '',
],
],
];
基本使用方法
使用门面(Facade)
<?php
namespace app\controller;
use think\facade\Filesystem;
use think\Request;
class FileController
{
/**
* 文件上传
*/
public function upload(Request $request)
{
// 验证文件
$file = $request->file('image');
// 保存文件到默认磁盘
$path = Filesystem::putFile('uploads', $file);
// 指定磁盘上传
$path = Filesystem::disk('public')->putFile('images', $file);
// 自定义文件名
$name = Filesystem::putFileAs('uploads', $file, 'custom-name.' . $file->extension());
return json([
'status' => 1,
'path' => $path,
'url' => Filesystem::disk('public')->url($path)
]);
}
/**
* 文件读取
*/
public function read($path)
{
// 读取文件内容
$content = Filesystem::get($path);
// 判断文件是否存在
$exists = Filesystem::has($path);
// 获取文件信息
$size = Filesystem::size($path);
$mime = Filesystem::mimeType($path);
$lastModified = Filesystem::lastModified($path);
return json([
'content' => $content,
'exists' => $exists,
'size' => $size,
'mime' => $mime,
'last_modified' => $lastModified
]);
}
/**
* 文件删除
*/
public function delete($path)
{
// 删除文件
$result = Filesystem::delete($path);
// 批量删除
$result = Filesystem::delete(['file1.txt', 'file2.txt']);
return json(['status' => $result ? 1 : 0]);
}
}
常用操作示例
文件上传
<?php
namespace app\controller;
use think\facade\Filesystem;
use think\Request;
class UploadController
{
public function upload(Request $request)
{
// 获取上传文件
$file = $request->file('file');
if (!$file) {
return json(['error' => '请选择文件']);
}
// 验证文件类型和大小
$validate = [
'size' => 1024 * 1024 * 2, // 2MB
'ext' => 'jpg,jpeg,png,gif'
];
if (!$file->check($validate)) {
return json(['error' => $file->getError()]);
}
// 移动到指定目录
$savePath = Filesystem::disk('public')->putFile('images', $file);
// 获取完整URL
$url = Filesystem::disk('public')->url($savePath);
// 获取文件信息
$info = [
'original_name' => $file->getOriginalName(),
'size' => $file->getSize(),
'extension' => $file->getExtension(),
'mime' => $file->getMime(),
'path' => $savePath,
'url' => $url
];
return json(['status' => 1, 'data' => $info]);
}
}
流式操作
<?php
namespace app\controller;
use think\facade\Filesystem;
class StreamController
{
/**
* 写入文件
*/
public function write()
{
// 写入内容
Filesystem::put('file.txt', 'Hello World');
// 追加内容
Filesystem::append('file.txt', ' - 追加内容');
// 写入流
$stream = fopen('path/to/local/file.txt', 'r');
Filesystem::writeStream('remote/file.txt', $stream);
return '写入完成';
}
/**
* 文件操作
*/
public function operations()
{
// 复制文件
Filesystem::copy('old/file.txt', 'new/file.txt');
// 移动文件
Filesystem::move('old/file.txt', 'new/file.txt');
// 创建目录
Filesystem::createDirectory('new/dir');
// 删除目录
Filesystem::deleteDirectory('old/dir');
// 列出目录内容
$files = Filesystem::listContents('dir', true);
foreach ($files as $file) {
echo $file['path'] . PHP_EOL;
}
}
}
自定义驱动
创建自定义驱动类
<?php
namespace app\filesystem;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Adapter\AbstractAdapter;
class CustomAdapter extends AbstractAdapter
{
protected $config;
public function __construct(array $config)
{
$this->config = $config;
}
// 实现必要的方法
public function write($path, $contents, array $config = [])
{
// 实现写入逻辑
}
public function writeStream($path, $resource, array $config = [])
{
// 实现流写入逻辑
}
public function update($path, $contents, array $config = [])
{
// 实现更新逻辑
}
// ... 其他必要方法
}
注册自定义驱动
<?php
// 在app/provider.php中注册
use think\filesystem\driver\Local;
use app\filesystem\CustomAdapter;
return [
'filesystem' => [
'extend' => [
'custom' => function ($app, $config) {
return new CustomAdapter($config);
},
],
],
];
使用Dependency Injection
<?php
namespace app\controller;
use think\filesystem\Filesystem;
class FileController
{
protected $filesystem;
public function __construct(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
public function index()
{
// 使用默认磁盘
$path = $this->filesystem->putFile('uploads', request()->file('file'));
// 指定磁盘
$path = $this->filesystem->disk('public')->putFile('uploads', request()->file('file'));
return $path;
}
}
注意事项
- 性能优化:对于大文件操作,建议使用流式处理
- 安全考虑:确保文件路径不会造成路径注入攻击
- 错误处理:始终处理可能的异常
- 权限设置:根据需求设置文件的可见性(public/private)
- 云存储适配:使用云存储时需要正确配置相关参数
这样你就掌握了ThinkPHP文件系统驱动的基本使用方法,根据项目需求,可以选择合适的存储方式(本地、OSS、COS等)。