flysystem v3 在 symfony 6.2 中读取文件元数据需用 listcontents() 提取 storageattributes 或组合 getsize()/lastmodified() 等方法,因 metadata() 已移除;listcontents() 支持递归、空路径静默返回,适配器能力各异,推荐注入 filesystemoperator 并捕获异常。

Flysystem 在 Symfony 6.2 中读取文件元数据,核心是通过 Filesystem 实例调用 listContents() 或 metadata() 方法,但需注意:Flysystem v3(Symfony 6.2 默认集成版本)**已移除独立的 metadata() 方法**,元数据需从 listContents() 结果中提取,或使用 fileExists() + getSize() / lastModified() 等组合获取。
使用 listContents() 批量获取元数据
该方法返回一个 Iterator,每个条目是 StorageAttributes 对象(来自 League\Flysystem\StorageAttributes),包含路径、类型、大小、最后修改时间等信息:
- 支持递归扫描目录(传
true第二个参数) - 只对已存在路径有效;不存在路径不报错,但返回空迭代器
- 部分适配器(如本地、S3)能返回完整元数据;FTP 等可能仅返回部分字段
示例:
使用 Kadence 主题作为 WordPress 项目的设计系统,涵盖设计令牌、布局系统、页头/页脚/导航设置以及页面/归档/单篇文章模板。
$filesystem = $this->filesystems->get('my_storage');
$contents = $filesystem->listContents('uploads/photo.jpg', false); // 单文件模式
foreach ($contents as $attributes) {
if ($attributes->isFile()) {
echo $attributes->path(); // 'uploads/photo.jpg'
echo $attributes->fileSize(); // int 字节大小
echo $attributes->lastModified(); // Unix 时间戳
echo $attributes->mimeType(); // string,如 'image/jpeg'(非所有适配器都支持)
}
}
按需获取单个文件关键元数据
当只需大小或修改时间时,推荐直接调用对应方法,更轻量且兼容性更好:
-
getSize(string $path): int— 返回字节数,文件不存在抛FileNotFound -
lastModified(string $path): int— 返回 Unix 时间戳,同上异常策略 -
mimeType(string $path): string— 需适配器支持(如 S3、本地),否则可能 fallback 到基于扩展名的猜测
示例:
phptry {
$size = $filesystem->getSize('docs/report.pdf');
$mtime = $filesystem->lastModified('docs/report.pdf');
$type = $filesystem->mimeType('docs/report.pdf');
$meta = [
'size' => $size,
'modified' => \DateTimeImmutable::createFromFormat('U', (string)$mtime),
'type' => $type,
];
} catch (FileNotFound $e) {
// 处理文件不存在
}
注意适配器能力差异
不是所有存储后端都能提供完整元数据:
- 本地适配器:支持全部(
fileSize、lastModified、mimeType、visibility) - AWS S3 适配器:支持
fileSize、lastModified、mimeType(来自 S3 的Content-Type头) - FTP 适配器:通常仅支持
lastModified和fileSize,mimeType不可用 - 内存适配器(测试用):仅模拟基础字段,
mimeType恒为null
建议在业务逻辑中做兜底处理,例如:
php$mimeType = $filesystem->mimeType($path) ?: 'application/octet-stream';
在 Symfony 控制器中安全使用
推荐注入 FilesystemOperator 接口(而非具体类),并配合异常处理:
- 声明类型提示为
FilesystemOperator,利于测试和替换 - 捕获
FileNotFound、UnableToRetrieveMetadata等特定异常 - 避免在循环中反复调用多个元数据方法——优先用
listContents()一次性获取
示例服务调用:
phpuse League\Flysystem\FilesystemOperator;
use League\Flysystem\UnableToRetrieveMetadata;
public function getFileInfo(FilesystemOperator $storage, string $path): array
{
try {
return [
'exists' => $storage->fileExists($path),
'size' => $storage->getSize($path),
'modified' => $storage->lastModified($path),
'type' => $storage->mimeType($path) ?? 'unknown',
];
} catch (UnableToRetrieveMetadata $e) {
return ['error' => 'metadata_unavailable', 'path' => $path];
}
}










