文件系统 / 云存储
介绍
Laravel 提供了一个出色的文件系统抽象,这要归功于 Frank de Jonge 的 Flysystem PHP 包。Laravel 的 Flysystem 集成为使用本地文件系统、Amazon S3 和 Rackspace 云存储提供了简单易用的驱动程序。更好的是,切换这些存储选项非常简单,因为每个系统的 API 都保持不变!
配置
文件系统配置文件位于 config/filesystems.php
。在此文件中,您可以配置所有的“磁盘”。每个磁盘代表一个特定的存储驱动程序和存储位置。配置文件中包含了每个支持的驱动程序的示例配置。因此,只需修改配置以反映您的存储偏好和凭据即可!
在使用 S3 或 Rackspace 驱动程序之前,您需要通过 Composer 安装相应的包:
- Amazon S3:
league/flysystem-aws-s3-v2 ~1.0
- Rackspace:
league/flysystem-rackspace ~1.0
当然,您可以配置任意数量的磁盘,甚至可以有多个使用相同驱动程序的磁盘。
使用 local
驱动程序时,请注意所有文件操作都是相对于配置文件中定义的 root
目录的。默认情况下,此值设置为 storage/app
目录。因此,以下方法将文件存储在 storage/app/file.txt
中:
Storage::disk('local')->put('file.txt', 'Contents');
基本用法
可以使用 Storage
facade 与任何已配置的磁盘进行交互。或者,您可以在通过 Laravel 服务容器 解析的任何类上类型提示 Illuminate\Contracts\Filesystem\Factory
合约。
检索特定磁盘
$disk = Storage::disk('s3');
$disk = Storage::disk('local');
确定文件是否存在
$exists = Storage::disk('s3')->exists('file.jpg');
在默认磁盘上调用方法
if (Storage::exists('file.jpg'))
{
//
}
检索文件内容
$contents = Storage::get('file.jpg');
设置文件内容
Storage::put('file.jpg', $contents);
在文件前添加内容
Storage::prepend('file.log', 'Prepended Text');
在文件后追加内容
Storage::append('file.log', 'Appended Text');
删除文件
Storage::delete('file.jpg');
Storage::delete(['file1.jpg', 'file2.jpg']);
将文件复制到新位置
Storage::copy('old/file1.jpg', 'new/file1.jpg');
将文件移动到新位置
Storage::move('old/file1.jpg', 'new/file1.jpg');
获取文件大小
$size = Storage::size('file1.jpg');
获取最后修改时间(UNIX)
$time = Storage::lastModified('file1.jpg');
获取目录中的所有文件
$files = Storage::files($directory);
// 递归...
$files = Storage::allFiles($directory);
获取目录中的所有目录
$directories = Storage::directories($directory);
// 递归...
$directories = Storage::allDirectories($directory);
创建目录
Storage::makeDirectory($directory);
删除目录
Storage::deleteDirectory($directory);
自定义文件系统
Laravel 的 Flysystem 集成为多个“驱动程序”提供了开箱即用的驱动程序;然而,Flysystem 并不限于这些,并且有许多其他存储系统的适配器。如果您想在 Laravel 应用程序中使用这些额外的适配器之一,可以创建自定义驱动程序。别担心,这并不难!
为了设置自定义文件系统,您需要创建一个服务提供者,例如 DropboxFilesystemServiceProvider
。在提供者的 boot
方法中,您可以注入 Illuminate\Contracts\Filesystem\Factory
合约的实例,并调用注入实例的 extend
方法。或者,您可以使用 Disk
facade 的 extend
方法。
extend
方法的第一个参数是驱动程序的名称,第二个是接收 $app
和 $config
变量的闭包。解析器闭包必须返回 League\Flysystem\Filesystem
的实例。
$config
变量将已经包含在 config/filesystems.php
中为指定磁盘定义的值。
Dropbox 示例
<?php namespace App\Providers;
use Storage;
use League\Flysystem\Filesystem;
use Dropbox\Client as DropboxClient;
use League\Flysystem\Dropbox\DropboxAdapter;
use Illuminate\Support\ServiceProvider;
class DropboxFilesystemServiceProvider extends ServiceProvider {
public function boot()
{
Storage::extend('dropbox', function($app, $config)
{
$client = new DropboxClient($config['accessToken'], $config['clientIdentifier']);
return new Filesystem(new DropboxAdapter($client));
});
}
public function register()
{
//
}
}