イントロダクションIntroduction
Laravelは、Frankde Jongeによる素晴らしいFlysystem PHPパッケージのおかげで、ファイルシステムの強力な抽象化を提供しています。Laravel Flysystem統合は、ローカルファイルシステム、SFTP、およびAmazonS3を操作するためのシンプルなドライバを提供します。さらに良いことに、APIは各システムで同じままであるため、ローカル開発マシンと本番サーバの間でこれらのストレージオプションを切り替えるのは驚くほど簡単です。Laravel provides a powerful filesystem abstraction thanks to the wonderful Flysystem[https://github.com/thephpleague/flysystem] PHP package by Frank de Jonge. The Laravel Flysystem integration provides simple drivers for working with local filesystems, SFTP, and Amazon S3. Even better, it's amazingly simple to switch between these storage options between your local development machine and production server as the API remains the same for each system.
設定Configuration
Laravelのファイルシステム設定ファイルはconfig/filesystems.phpにあります。このファイル内で、すべてのファイルシステム「ディスク」を設定できます。各ディスクは、特定のストレージドライバとストレージの場所を表します。サポートしている各ドライバの設定例を設定ファイルに用意しているので、ストレージ設定と資格情報を反映するように設定を変更してください。Laravel's filesystem
configuration file is located at
config/filesystems.php. Within this
file, you may configure all of your filesystem
"disks". Each disk represents a particular
storage driver and storage location. Example
configurations for each supported driver are
included in the configuration file so you can modify
the configuration to reflect your storage
preferences and credentials.
localドライバは、Laravelアプリケーションを実行しているサーバでローカルに保存されているファイルを操作し、s3ドライバはAmazonのS3クラウドストレージサービスへの書き込みに使用します。The local driver
interacts with files stored locally on the server
running the Laravel application while the
s3 driver is used to write to Amazon's
S3 cloud storage service.
Note: 必要な数のディスクを構成でき、同じドライバを使用する複数のディスクを使用することもできます。[!NOTE]
You may configure as many disks as you like and may even have multiple disks that use the same driver.
ローカルドライバThe Local Driver
localドライバを使用する場合、すべてのファイル操作は、filesystems設定ファイルで定義したrootディレクトリからの相対位置です。デフォルトでは、この値はstorage/appディレクトリに設定されています。したがって、次のメソッドはstorage/app/example.txtに書き込みます。When using the local
driver, all file operations are relative to the
root directory defined in your
filesystems configuration file. By
default, this value is set to the
storage/app directory. Therefore, the
following method would write to
storage/app/example.txt:
use Illuminate\Support\Facades\Storage;
Storage::disk('local')->put('example.txt', 'Contents');
公開ディスクThe Public Disk
アプリケーションのfilesystems設定ファイルに含まれているpublicディスクは、パブリックに公開してアクセスできるようにするファイルを対象としています。デフォルトでは、publicディスクはlocalドライバを使用し、そのファイルをstorage/app/publicに保存します。The public disk
included in your application's
filesystems configuration file is
intended for files that are going to be publicly
accessible. By default, the public disk
uses the local driver and stores its
files in storage/app/public.
これらのファイルにWebからアクセスできるようにするには、public/storageからstorage/app/publicへのシンボリックリンクを作成する必要があります。このフォルダ規約を利用すると、Envoyerのようなダウンタイムゼロのデプロイメントシステムを使用する場合に、パブリックにアクセス可能なファイルを1つのディレクトリに保持し、デプロイメント間で簡単に共有できます。To make these files accessible
from the web, you should create a symbolic link from
public/storage to
storage/app/public. Utilizing this
folder convention will keep your publicly accessible
files in one directory that can be easily shared
across deployments when using zero down-time
deployment systems like
Envoyer[https://envoyer.io].
シンボリックリンクを作成するには、storage:link
Artisanコマンドを使用できます。To create
the symbolic link, you may use the
storage:link Artisan
command:
php artisan storage:link
ファイルを保存し、シンボリックリンクを作成したら、assetヘルパを使用してファイルへのURLを作成できます。Once a file has been stored and
the symbolic link has been created, you can create a
URL to the files using the asset
helper:
echo asset('storage/file.txt');
filesystems設定ファイルで追加のシンボリックリンクを設定できます。storage:linkコマンドを実行すると、設定された各リンクが作成されます。You may configure additional
symbolic links in your filesystems
configuration file. Each of the configured links
will be created when you run the
storage:link command:
'links' => [
public_path('storage') => storage_path('app/public'),
public_path('images') => storage_path('app/images'),
],
設定したシンボリックリンクを破棄するには、storage:unlink
コマンドを使用します。The
storage:unlink command may be used to
destroy your configured symbolic links:
php artisan storage:unlink
ドライバの動作要件Driver Prerequisites
S3ドライバ設定S3 Driver Configuration
S3ドライバを使用する前に、Composerパッケージマネージャを使用し、Flysystem S3パッケージをインストールする必要があります。Before using the S3 driver, you will need to install the Flysystem S3 package via the Composer package manager:
composer require league/flysystem-aws-s3-v3 "^3.0" --with-all-dependencies
S3ディスク設定配列は、config/filesystems.php
設定ファイルにあります。通常は、config/filesystems.php設定ファイルから参照されている以下の環境変数を使い、S3の情報と認証情報を設定します。An S3 disk configuration array is
located in your config/filesystems.php
configuration file. Typically, you should configure
your S3 information and credentials using the
following environment variables which are referenced
by the config/filesystems.php
configuration file:
AWS_ACCESS_KEY_ID=<your-key-id>
AWS_SECRET_ACCESS_KEY=<your-secret-access-key>
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=<your-bucket-name>
AWS_USE_PATH_STYLE_ENDPOINT=false
わかりやすいように、これらの環境変数はAWS CLIで使用されている命名規則と一致させています。For convenience, these environment variables match the naming convention used by the AWS CLI.
FTPドライバの設定FTP Driver Configuration
FTPドライバを使用する前に、Composerパッケージマネージャを使用し、Flysystem FTPパッケージをインストールする必要があります。Before using the FTP driver, you will need to install the Flysystem FTP package via the Composer package manager:
composer require league/flysystem-ftp "^3.0"
LaravelのFlysystemの統合は、FTPでもうまく動作しますが、フレームワークのデフォルトのconfig/filesystems.php設定ファイルにサンプル設定は、用意していません。FTPファイルシステムを設定する必要がある場合は、以下の設定例を使用してください。Laravel's Flysystem integrations
work great with FTP; however, a sample configuration
is not included with the framework's default
config/filesystems.php configuration
file. If you need to configure an FTP filesystem,
you may use the configuration example
below:
'ftp' => [
'driver' => 'ftp',
'host' => env('FTP_HOST'),
'username' => env('FTP_USERNAME'),
'password' => env('FTP_PASSWORD'),
// オプションのFTP設定
// 'port' => env('FTP_PORT', 21),
// 'root' => env('FTP_ROOT'),
// 'passive' => true,
// 'ssl' => true,
// 'timeout' => 30,
],
SFTPドライバの設定SFTP Driver Configuration
SFTPドライバを使用する前に、Composerパッケージマネージャを使用して Flysystem SFTPパッケージをインストールする必要があります。Before using the SFTP driver, you will need to install the Flysystem SFTP package via the Composer package manager:
composer require league/flysystem-sftp-v3 "^3.0"
LaravelのFlysystemの統合は、SFTPでもうまく動作しますが、フレームワークのデフォルトのconfig/filesystems.php設定ファイルにサンプル設定は、用意していません。SFTPファイルシステムを設定する必要がある場合は、以下の設定例を使用してください:Laravel's Flysystem integrations
work great with SFTP; however, a sample
configuration is not included with the framework's
default config/filesystems.php
configuration file. If you need to configure an SFTP
filesystem, you may use the configuration example
below:
'sftp' => [
'driver' => 'sftp',
'host' => env('SFTP_HOST'),
// 基本認証の設定
'username' => env('SFTP_USERNAME'),
'password' => env('SFTP_PASSWORD'),
// 暗号化パスワードを使用するSSHキーベースの認証の設定
'privateKey' => env('SFTP_PRIVATE_KEY'),
'passphrase' => env('SFTP_PASSPHRASE'),
// Settings for file / directory permissions...
'visibility' => 'private', // `private` = 0600, `public` = 0644
'directory_visibility' => 'private', // `private` = 0700, `public` = 0755
// オプションのSFTP設定
// 'hostFingerprint' => env('SFTP_HOST_FINGERPRINT'),
// 'maxTries' => 4,
// 'passphrase' => env('SFTP_PASSPHRASE'),
// 'port' => env('SFTP_PORT', 22),
// 'root' => env('SFTP_ROOT', ''),
// 'timeout' => 30,
// 'useAgent' => true,
],
スコープ付きと読み取り専用ファイルシステムScoped and Read-Only Filesystems
スコープ付きディスクを使用すると、すべてのパスに自動的に指定したパスプレフィックスが付くファイルシステムを定義できます。スコープ付きファイルシステムディスクを作成する前に、Composerパッケージマネージャを使用して、Flysystemパッケージを追加でインストールする必要があります。Scoped disks allow you to define a filesystem where all paths are automatically prefixed with a given path prefix. Before creating a scoped filesystem disk, you will need to install an additional Flysystem package via the Composer package manager:
composer require league/flysystem-path-prefixing "^3.0"
scopedドライバを利用するディスクを定義し、既存のファイルシステムディスクをパススコープするインスタンスを作成します。例えば、既存のs3ディスクを特定のパスプレフィックスにスコープするディスクを作成すれば、スコープしたディスクを使用するすべてのファイル操作で、指定したプレフィックスを使用します。You may create a path scoped
instance of any existing filesystem disk by defining
a disk that utilizes the scoped driver.
For example, you may create a disk which scopes your
existing s3 disk to a specific path
prefix, and then every file operation using your
scoped disk will utilize the specified
prefix:
's3-videos' => [
'driver' => 'scoped',
'disk' => 's3',
'prefix' => 'path/to/videos',
],
「読み取り専用(Read-only)」ディスクで、書き込み操作を許可しないファイルシステムディスクを作成できます。read-only設定オプションを使用する前に、Composerパッケージマネージャ経由で、Flysystemパッケージを追加インストールする必要があります。"Read-only" disks allow
you to create filesystem disks that do not allow
write operations. Before using the
read-only configuration option, you
will need to install an additional Flysystem package
via the Composer package manager:
composer require league/flysystem-read-only "^3.0"
次に、ディスクの設定配列に、read-only設定オプションを含めてください。Next, you may include the
read-only configuration option in one
or more of your disk's configuration
arrays:
's3-videos' => [
'driver' => 's3',
// ...
'read-only' => true,
],
Amazon S3コンパチファイルシステムAmazon S3 Compatible Filesystems
アプリケーションのfilesystems設定ファイルはデフォルトで、s3ディスクのディスク設定を含んでいます。このディスクはAmazon
S3の操作に加え、MinIOやDigitalOcean
Spacesなど、S3と互換性のあるファイルストレージサービスの操作にも使用できます。By default, your application's
filesystems configuration file contains
a disk configuration for the s3 disk.
In addition to using this disk to interact with
Amazon S3, you may use it to interact with any S3
compatible file storage service such as
MinIO[https://github.com/minio/minio] or
DigitalOcean
Spaces[https://www.digitalocean.com/products/spaces/].
通常、ディスクの認証情報を使用予定のサービス認証情報へ合わせて更新した後に、endpoint設定オプションの値を更新するだけで済みます。このオプションの値は通常、AWS_ENDPOINT環境変数で定義されています。Typically, after updating the
disk's credentials to match the credentials of the
service you are planning to use, you only need to
update the value of the endpoint
configuration option. This option's value is
typically defined via the AWS_ENDPOINT
environment variable:
'endpoint' => env('AWS_ENDPOINT', 'https://minio:9000'),
MinIOMinIO
LaravelのFlysystemインテグレーションでMinIOを使用する際に、適切なURLを生成するには、AWS_URL環境変数を定義し、アプリケーションのローカルURLと一致させ、URLパスにバケット名を含める必要があります。In order for Laravel's Flysystem
integration to generate proper URLs when using
MinIO, you should define the AWS_URL
environment variable so that it matches your
application's local URL and includes the bucket name
in the URL path:
AWS_URL=http://localhost:9000/local
Warning! MinIOを使用する場合、
temporaryUrlメソッドによる一時保存用URLの生成はサポートしていません。[!WARNING]
Generating temporary storage URLs via thetemporaryUrlmethod is not supported when using MinIO.
ディスクインスタンスの取得Obtaining Disk Instances
Storageファサードは、設定済みのディスクと対話するために使用できます。たとえば、ファサードでputメソッドを使用して、アバターをデフォルトのディスクに保存できます。最初にdiskメソッドを呼び出さずにStorageファサードのメソッドを呼び出すと、メソッドは自動的にデフォルトのディスクに渡されます。The Storage facade
may be used to interact with any of your configured
disks. For example, you may use the put
method on the facade to store an avatar on the
default disk. If you call methods on the
Storage facade without first calling
the disk method, the method will
automatically be passed to the default
disk:
use Illuminate\Support\Facades\Storage;
Storage::put('avatars/1', $content);
アプリケーションが複数のディスクを操作する場合は、Storageファサードでdiskメソッドを使用し、特定のディスク上のファイルを操作できます。If your application interacts
with multiple disks, you may use the
disk method on the Storage
facade to work with files on a particular
disk:
Storage::disk('s3')->put('avatars/1', $content);
オンデマンドディスクOn-Demand Disks
時には、アプリケーションのfilesystems設定ファイルに実際にその構成が存在しなくても、指定する構成を使用して実行時にディスクを作成したい場合があります。これを実現するため、Storageファサードのbuildメソッドへ設定配列を渡せます。Sometimes you may wish to create
a disk at runtime using a given configuration
without that configuration actually being present in
your application's filesystems
configuration file. To accomplish this, you may pass
a configuration array to the Storage
facade's build method:
use Illuminate\Support\Facades\Storage;
$disk = Storage::build([
'driver' => 'local',
'root' => '/path/to/root',
]);
$disk->put('image.jpg', $content);
ファイルの取得Retrieving Files
getメソッドを使用して、ファイルの内容を取得できます。ファイルの素の文字列の内容は、メソッドによって返されます。すべてのファイルパスは、ディスクの「ルート」の場所を基準にして指定する必要があることに注意してください。The get method may
be used to retrieve the contents of a file. The raw
string contents of the file will be returned by the
method. Remember, all file paths should be specified
relative to the disk's "root"
location:
$contents = Storage::get('file.jpg');
取得するファイルがJSONを含んでいる場合、jsonメソッドを使用してファイルを取得し、その内容をデコードできます。If the file you are retrieving
contains JSON, you may use the json
method to retrieve the file and decode its
contents:
$orders = Storage::json('orders.json');
existsメソッドを使用して、ファイルがディスクに存在するかどうかを判定できます。The exists method
may be used to determine if a file exists on the
disk:
if (Storage::disk('s3')->exists('file.jpg')) {
// ...
}
missingメソッドを使用して、ファイルがディスク存在していないことを判定できます。The missing method
may be used to determine if a file is missing from
the disk:
if (Storage::disk('s3')->missing('file.jpg')) {
// ...
}
ファイルのダウンロードDownloading Files
downloadメソッドを使用して、ユーザーのブラウザに指定したパスでファイルをダウンロードするように強制するレスポンスを生成できます。downloadメソッドは、メソッドの2番目の引数としてファイル名を受け入れます。これにより、ユーザーがファイルをダウンロードするときに表示されるファイル名が決まります。最後に、HTTPヘッダの配列をメソッドの3番目の引数として渡すことができます。The download method
may be used to generate a response that forces the
user's browser to download the file at the given
path. The download method accepts a
filename as the second argument to the method, which
will determine the filename that is seen by the user
downloading the file. Finally, you may pass an array
of HTTP headers as the third argument to the
method:
return Storage::download('file.jpg');
return Storage::download('file.jpg', $name, $headers);
ファイルのURLFile URLs
urlメソッドを使用し、特定のファイルのURLを取得できます。localドライバを使用している場合、これは通常、指定されたパスの前に/storageを追加し、ファイルへの相対URLを返します。s3ドライバを使用している場合は、完全修飾リモートURLが返されます。You may use the url
method to get the URL for a given file. If you are
using the local driver, this will
typically just prepend /storage to the
given path and return a relative URL to the file. If
you are using the s3 driver, the fully
qualified remote URL will be returned:
use Illuminate\Support\Facades\Storage;
$url = Storage::url('file.jpg');
localドライバを使用する場合、パブリックにアクセス可能である必要があるすべてのファイルは、storage/app/publicディレクトリに配置する必要があります。さらに、storage/app/publicディレクトリを指すpublic/storageにシンボリックリンクを作成する必要があります。When using the local
driver, all files that should be publicly accessible
should be placed in the
storage/app/public directory.
Furthermore, you should create a symbolic
link[#the-public-disk] at
public/storage which points to the
storage/app/public
directory.
Warning!
localドライバを使用する場合、urlの戻り値はURLエンコードされません。このため、常に有効なURLを作成する名前を使用してファイルを保存することをお勧めします。[!WARNING]
When using thelocaldriver, the return value ofurlis not URL encoded. For this reason, we recommend always storing your files using names that will create valid URLs.
URLホストのカスタマイズURL Host Customization
Storageファサードを使用して生成したURLのホストを変更したい場合は、ディスクの設定配列へurlオプションを追加または変更してください。If you would like to modify the
host for URLs generated using the
Storage facade, you may add or change
the url option in the disk's
configuration array:
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
一時的なURLTemporary URLs
temporaryUrlメソッドを使用すると、s3ドライバを使用して保存されたファイルへの一時URLを作成できます。このメソッドは、パスと、URLの有効期限を指定するDateTimeインスタンスを受け入れます。Using the
temporaryUrl method, you may create
temporary URLs to files stored using the
s3 driver. This method accepts a path
and a DateTime instance specifying when
the URL should expire:
use Illuminate\Support\Facades\Storage;
$url = Storage::temporaryUrl(
'file.jpg', now()->addMinutes(5)
);
追加のS3リクエストパラメーターを指定する必要がある場合は、リクエストパラメーターの配列をtemporaryUrlメソッドの引数の3番目として渡すことができます。If you need to specify additional
S3 request
parameters[https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html#RESTObjectGET-requests],
you may pass the array of request parameters as the
third argument to the temporaryUrl
method:
$url = Storage::temporaryUrl(
'file.jpg',
now()->addMinutes(5),
[
'ResponseContentType' => 'application/octet-stream',
'ResponseContentDisposition' => 'attachment; filename=file2.jpg',
]
);
特定するストレージディスクに対する一時的なURLの生成方法をカスタマイズする必要がある場合、
buildTemporaryUrlsUsing
メソッドを使用してください。例えば、一時的なURLを通常サポートしていないディスクに保存されているファイルをダウンロードできるコントローラがある場合、これは便利です。通常、このメソッドはサービスプロバイダのbootメソッドから呼び出します。If you need to customize how
temporary URLs are created for a specific storage
disk, you can use the
buildTemporaryUrlsUsing method. For
example, this can be useful if you have a controller
that allows you to download files stored via a disk
that doesn't typically support temporary URLs.
Usually, this method should be called from the
boot method of a service
provider:
<?php
namespace App\Providers;
use DateTime;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* 全アプリケーションサービスの初期起動処理
*/
public function boot(): void
{
Storage::disk('local')->buildTemporaryUrlsUsing(
function (string $path, DateTime $expiration, array $options) {
return URL::temporarySignedRoute(
'files.download',
$expiration,
array_merge($options, ['path' => $path])
);
}
);
}
}
一時的なアップロードURLTemporary Upload URLs
Warning! 一時的なアップロードURLの生成機能は、
s3ドライバのみサポートしています。[!WARNING]
The ability to generate temporary upload URLs is only supported by thes3driver.
クライアントサイドのアプリケーションから、直接ファイルをアップロードするために使用する一時的なURLを生成する必要がある場合は、temporaryUploadUrlメソッドを使用します。このメソッドには、パスとURLの有効期限を指定するDateTimeインスタンスを指定します。temporaryUploadUrlメソッドからは、アップロードURLとアップロードリクエストに含めるべきヘッダを連想配列で返します。If you need to generate a
temporary URL that can be used to upload a file
directly from your client-side application, you may
use the temporaryUploadUrl method. This
method accepts a path and a DateTime
instance specifying when the URL should expire. The
temporaryUploadUrl method returns an
associative array which may be destructured into the
upload URL and the headers that should be included
with the upload request:
use Illuminate\Support\Facades\Storage;
['url' => $url, 'headers' => $headers] = Storage::temporaryUploadUrl(
'file.jpg', now()->addMinutes(5)
);
このメソッドは、主にクライアントサイドのアプリケーションがAmazon S3などのクラウドストレージシステムに直接ファイルをアップロードする必要があるサーバレス環境で役立つでしょう。This method is primarily useful in serverless environments that require the client-side application to directly upload files to a cloud storage system such as Amazon S3.
ファイルメタデータFile Metadata
Laravelは、ファイルの読み取りと書き込みに加えて、ファイル自体に関する情報も提供できます。たとえば、sizeメソッドを使用して、ファイルのサイズをバイト単位で取得できます。In addition to reading and
writing files, Laravel can also provide information
about the files themselves. For example, the
size method may be used to get the size
of a file in bytes:
use Illuminate\Support\Facades\Storage;
$size = Storage::size('file.jpg');
lastModifiedメソッドは、ファイルが最後に変更されたときのUNIXタイムスタンプを返します。The lastModified
method returns the UNIX timestamp of the last time
the file was modified:
$time = Storage::lastModified('file.jpg');
指定ファイルのMIMEタイプは、mimeTypeメソッドで取得できます。The MIME type of a given file may
be obtained via the mimeType
method:
$mime = Storage::mimeType('file.jpg');
ファイルパスFile Paths
pathメソッドを使用して、特定のファイルのパスを取得できます。localドライバを使用している場合、これはファイルへの絶対パスを返します。s3ドライバを使用している場合、このメソッドはS3バケット内のファイルへの相対パスを返します。You may use the path
method to get the path for a given file. If you are
using the local driver, this will
return the absolute path to the file. If you are
using the s3 driver, this method will
return the relative path to the file in the S3
bucket:
use Illuminate\Support\Facades\Storage;
$path = Storage::path('file.jpg');
ファイルの保存Storing Files
putメソッドは、ファイルの内容をディスクに保存するために使用します。PHPのresourceをputメソッドに渡すこともできます。このメソッドは、Flysystemの基盤となるストリームサポートを使用します。すべてのファイルパスは、ディスク用に設定された「ルート」の場所を基準にして指定する必要があることに注意してください。The put method may
be used to store file contents on a disk. You may
also pass a PHP resource to the
put method, which will use Flysystem's
underlying stream support. Remember, all file paths
should be specified relative to the "root"
location configured for the disk:
use Illuminate\Support\Facades\Storage;
Storage::put('file.jpg', $contents);
Storage::put('file.jpg', $resource);
書き込みの失敗Failed Writes
putメソッド、もしくは他の「書き込み」操作でディスクへファイルを書き込めない場合は、falseが返ります。If the put method
(or other "write" operations) is unable to
write the file to disk, false will be
returned:
if (! Storage::put('file.jpg', $contents)) {
// ファイルがディスクへ書き込めなかった
}
必要であれば、ファイルシステムのディスクの設定配列で、throwオプションを定義できます。このオプションをtrueに定義すると、putのような「書き込み」メソッドの書き込み失敗時に、League\Flysystem\UnableToWriteFileインスタンスを投げます。If you wish, you may define the
throw option within your filesystem
disk's configuration array. When this option is
defined as true, "write"
methods such as put will throw an
instance of
League\Flysystem\UnableToWriteFile when
write operations fail:
'public' => [
'driver' => 'local',
// ...
'throw' => true,
],
ファイルの前後への追加Prepending and Appending To Files
prependおよびappendメソッドを使用すると、ファイルの最初または最後に書き込むことができます。The prepend and
append methods allow you to write to
the beginning or end of a file:
Storage::prepend('file.log', 'Prepended Text');
Storage::append('file.log', 'Appended Text');
ファイルのコピーと移動Copying and Moving Files
copyメソッドを使用して、既存のファイルをディスク上の新しい場所にコピーできます。また、moveメソッドを使用して、既存のファイルの名前を変更したり、新しい場所に移動したりできます。The copy method may
be used to copy an existing file to a new location
on the disk, while the move method may
be used to rename or move an existing file to a new
location:
Storage::copy('old/file.jpg', 'new/file.jpg');
Storage::move('old/file.jpg', 'new/file.jpg');
自動ストリーミングAutomatic Streaming
ファイルをストレージにストリーミングすると、メモリ使用量が大幅に削減されます。Laravelに特定のファイルの保存場所へのストリーミングを自動的に管理させたい場合は、putFileまたはputFileAsメソッドを使用します。このメソッドは、Illuminate\Http\FileまたはIlluminate\Http\UploadedFileインスタンスのいずれかを引数に取り、ファイルを目的の場所へ自動的にストリーミングします。Streaming files to storage offers
significantly reduced memory usage. If you would
like Laravel to automatically manage streaming a
given file to your storage location, you may use the
putFile or putFileAs
method. This method accepts either an
Illuminate\Http\File or
Illuminate\Http\UploadedFile instance
and will automatically stream the file to your
desired location:
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
// ファイル名の一意のIDを自動的に生成
$path = Storage::putFile('photos', new File('/path/to/photo'));
// ァイル名を手作業で指定
$path = Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');
putFileメソッドには注意すべき重要な点がいくつかあります。ファイル名ではなく、ディレクトリ名のみを指定することに注意してください。デフォルトでは、putFileメソッドはファイル名として働く一意のIDを生成します。ファイルの拡張子は、ファイルのMIMEタイプを調べることによって決定されます。ファイルへのパスはputFileメソッドが返すため、生成されたファイル名を含むパスをデータベースへ保存できます。There are a few important things
to note about the putFile method. Note
that we only specified a directory name and not a
filename. By default, the putFile
method will generate a unique ID to serve as the
filename. The file's extension will be determined by
examining the file's MIME type. The path to the file
will be returned by the putFile method
so you can store the path, including the generated
filename, in your database.
putFileメソッドとputFileAsメソッドは、保存するファイルの「可視性」を指定する引数も取ります。これは、AmazonS3などのクラウドディスクにファイルを保存していて、生成されたURLを介してファイルへパブリックアクセスできるようにする場合、特に便利です。The putFile and
putFileAs methods also accept an
argument to specify the "visibility" of
the stored file. This is particularly useful if you
are storing the file on a cloud disk such as Amazon
S3 and would like the file to be publicly accessible
via generated URLs:
Storage::putFile('photos', new File('/path/to/photo'), 'public');
ファイルのアップロードFile Uploads
Webアプリケーションでは、ファイルを保存するための最も一般的な使用例の1つは、写真やドキュメントなどのユーザーがアップロードしたファイルを保存することです。Laravelを使用すると、アップロードされたファイルインスタンスにstoreメソッドを使用し、ファイルを非常に簡単に保存できます。アップロード済みファイルを保存するパスを指定してstoreメソッドを呼び出します。In web applications, one of the
most common use-cases for storing files is storing
user uploaded files such as photos and documents.
Laravel makes it very easy to store uploaded files
using the store method on an uploaded
file instance. Call the store method
with the path at which you wish to store the
uploaded file:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserAvatarController extends Controller
{
/**
* ユーザーのアバターを更新
*/
public function update(Request $request): string
{
$path = $request->file('avatar')->store('avatars');
return $path;
}
}
この例で注意すべき重要なことがあります。ファイル名ではなく、ディレクトリ名のみを指定したことに注意してください。デフォルトでは、storeメソッドはファイル名として機能する一意のIDを生成します。ファイルの拡張子は、ファイルのMIMEタイプを調べることによって決定されます。ファイルへのパスはstoreメソッドによって返されるため、生成されたファイル名を含むパスをデータベースに保存できます。There are a few important things
to note about this example. Note that we only
specified a directory name, not a filename. By
default, the store method will generate
a unique ID to serve as the filename. The file's
extension will be determined by examining the file's
MIME type. The path to the file will be returned by
the store method so you can store the
path, including the generated filename, in your
database.
StorageファサードでputFileメソッドを呼び出して、上記の例と同じファイルストレージ操作を実行することもできます。You may also call the
putFile method on the
Storage facade to perform the same file
storage operation as the example above:
$path = Storage::putFile('avatars', $request->file('avatar'));
ファイル名の指定Specifying a File Name
保存されたファイルにファイル名を自動的に割り当てたくない場合は、引数としてパス、ファイル名、および(オプションの)ディスクを受け取るstoreAsメソッドを使用します。If you do not want a filename to
be automatically assigned to your stored file, you
may use the storeAs method, which
receives the path, the filename, and the (optional)
disk as its arguments:
$path = $request->file('avatar')->storeAs(
'avatars', $request->user()->id
);
StorageファサードでputFileAsメソッドを使用することもできます。これにより、上記の例と同じファイルストレージ操作が実行されます。You may also use the
putFileAs method on the
Storage facade, which will perform the
same file storage operation as the example
above:
$path = Storage::putFileAs(
'avatars', $request->file('avatar'), $request->user()->id
);
Warning! 印刷できない無効なUnicode文字はファイルパスから自動的に削除されます。したがって、Laravelのファイルストレージメソッドに渡す前に、ファイルパスをサニタイズすることをお勧めします。ファイルパスは、
League\Flysystem\WhitespacePathNormalizer::normalizePathメソッドを使用して正規化されます。[!WARNING]
Unprintable and invalid unicode characters will automatically be removed from file paths. Therefore, you may wish to sanitize your file paths before passing them to Laravel's file storage methods. File paths are normalized using theLeague\Flysystem\WhitespacePathNormalizer::normalizePathmethod.
ディスクの指定Specifying a Disk
デフォルトでは、このアップロード済みファイルのstoreメソッドはデフォルトのディスクを使用します。別のディスクを指定する場合は、ディスク名を2番目の引数としてstoreメソッドに渡します。By default, this uploaded file's
store method will use your default
disk. If you would like to specify another disk,
pass the disk name as the second argument to the
store method:
$path = $request->file('avatar')->store(
'avatars/'.$request->user()->id, 's3'
);
storeAsメソッドを使用している場合は、ディスク名を3番目の引数としてメソッドに渡すことができます。If you are using the
storeAs method, you may pass the disk
name as the third argument to the method:
$path = $request->file('avatar')->storeAs(
'avatars',
$request->user()->id,
's3'
);
アップロード済みファイルのその他の情報Other Uploaded File Information
アップロードされたファイルの元の名前と拡張子を取得したい場合は、getClientOriginalNameとgetClientOriginalExtensionメソッドを使って取得します。If you would like to get the
original name and extension of the uploaded file,
you may do so using the
getClientOriginalName and
getClientOriginalExtension
methods:
$file = $request->file('avatar');
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
ただし,悪意のあるユーザーによりファイル名や拡張子が改竄される可能性があるため,getClientOriginalNameとgetClientOriginalExtensionメソッドは安全であると考えられないことに注意してください。そのため,アップロードされたファイルの名前と拡張子を取得するには,通常,hashNameメソッドとextensionメソッドを使用するべきです。However, keep in mind that the
getClientOriginalName and
getClientOriginalExtension methods are
considered unsafe, as the file name and extension
may be tampered with by a malicious user. For this
reason, you should typically prefer the
hashName and extension
methods to get a name and an extension for the given
file upload:
$file = $request->file('avatar');
$name = $file->hashName(); // ユニークでランダムな名前を生成する
$extension = $file->extension(); // ファイルのMIMEタイプに基づき拡張子を決める
ファイルの可視性File Visibility
LaravelのFlysystem統合では、「可視性」は複数のプラットフォームにわたるファイル権限の抽象化です。ファイルはpublicまたはprivateとして宣言できます。ファイルがpublicと宣言されている場合、そのファイルは一般的に他のユーザーがアクセスできる必要があることを示しています。たとえば、S3ドライバを使用する場合、publicファイルのURLを取得できます。In Laravel's Flysystem
integration, "visibility" is an
abstraction of file permissions across multiple
platforms. Files may either be declared
public or private. When a
file is declared public, you are
indicating that the file should generally be
accessible to others. For example, when using the S3
driver, you may retrieve URLs for
public files.
putメソッドを介してファイルを書き込むとき、可視性を設定できます。You can set the visibility when
writing the file via the put
method:
use Illuminate\Support\Facades\Storage;
Storage::put('file.jpg', $contents, 'public');
ファイルがすでに保存されている場合、その可視性は、getVisibilityおよびsetVisibilityメソッドにより取得および設定できます。If the file has already been
stored, its visibility can be retrieved and set via
the getVisibility and
setVisibility methods:
$visibility = Storage::getVisibility('file.jpg');
Storage::setVisibility('file.jpg', 'public');
アップロード済みファイルを操作するときは、storePubliclyメソッドとstorePubliclyAsメソッドを使用して、アップロード済みファイルをpublicの可視性で保存できます。When interacting with uploaded
files, you may use the storePublicly
and storePubliclyAs methods to store
the uploaded file with public
visibility:
$path = $request->file('avatar')->storePublicly('avatars', 's3');
$path = $request->file('avatar')->storePubliclyAs(
'avatars',
$request->user()->id,
's3'
);
ローカルファイルと可視性Local Files and Visibility
localドライバを使用する場合、publicの可視性は、ディレクトリの0755パーミッションとファイルの0644パーミッションに変換されます。アプリケーションのfilesystems設定ファイルでパーミッションマッピングを変更できます。When using the local
driver, public
visibility[#file-visibility] translates to
0755 permissions for directories and
0644 permissions for files. You can
modify the permissions mappings in your
application's filesystems configuration
file:
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'permissions' => [
'file' => [
'public' => 0644,
'private' => 0600,
],
'dir' => [
'public' => 0755,
'private' => 0700,
],
],
'throw' => false,
],
ファイルの削除Deleting Files
deleteメソッドは、削除する単一のファイル名またはファイルの配列を受け入れます。The delete method
accepts a single filename or an array of files to
delete:
use Illuminate\Support\Facades\Storage;
Storage::delete('file.jpg');
Storage::delete(['file.jpg', 'file2.jpg']);
必要に応じて、ファイルを削除するディスクを指定できます。If necessary, you may specify the disk that the file should be deleted from:
use Illuminate\Support\Facades\Storage;
Storage::disk('s3')->delete('path/file.jpg');
ディレクトリDirectories
ディレクトリ内のすべてのファイルを取得Get All Files Within a Directory
filesメソッドは、指定されたディレクトリ内のすべてのファイルの配列を返します。すべてのサブディレクトリを含む、特定のディレクトリ内のすべてのファイルのリストを取得する場合は、allFilesメソッドを使用できます。The files method
returns an array of all of the files in a given
directory. If you would like to retrieve a list of
all files within a given directory including all
subdirectories, you may use the
allFiles method:
use Illuminate\Support\Facades\Storage;
$files = Storage::files($directory);
$files = Storage::allFiles($directory);
ディレクトリ内のすべてのディレクトリを取得Get All Directories Within a Directory
directoriesメソッドは、指定されたディレクトリ内のすべてのディレクトリの配列を返します。さらに、allDirectoriesメソッドを使用して、特定のディレクトリ内のすべてのディレクトリとそのすべてのサブディレクトリのリストを取得できます。The directories
method returns an array of all the directories
within a given directory. Additionally, you may use
the allDirectories method to get a list
of all directories within a given directory and all
of its subdirectories:
$directories = Storage::directories($directory);
$directories = Storage::allDirectories($directory);
ディレクトリを作成するCreate a Directory
makeDirectoryメソッドは、必要なサブディレクトリを含む、指定したディレクトリを作成します。The makeDirectory
method will create the given directory, including
any needed subdirectories:
Storage::makeDirectory($directory);
ディレクトリを削除するDelete a Directory
最後に、deleteDirectoryメソッドを使用して、ディレクトリとそのすべてのファイルを削除できます。Finally, the
deleteDirectory method may be used to
remove a directory and all of its files:
Storage::deleteDirectory($directory);
テストTesting
Storageファサードのfakeメソッドを使うと、簡単に偽のディスクを生成できます。これをIlluminate\Http\UploadedFileクラスのファイル生成ユーティリティと組み合わせると、ファイルのアップロードのテストが非常に簡単になります。例えば、以下のようにです。The Storage facade's
fake method allows you to easily
generate a fake disk that, combined with the file
generation utilities of the
Illuminate\Http\UploadedFile class,
greatly simplifies the testing of file uploads. For
example:
<?php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
test('albums can be uploaded', function () {
Storage::fake('photos');
$response = $this->json('POST', '/photos', [
UploadedFile::fake()->image('photo1.jpg'),
UploadedFile::fake()->image('photo2.jpg')
]);
// 一つ以上のファイルを保存することをアサート
Storage::disk('photos')->assertExists('photo1.jpg');
Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']);
// ファイルを保存しないことをアサート
Storage::disk('photos')->assertMissing('missing.jpg');
Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']);
// 指定ディレクトリが空であることをアサート
Storage::disk('photos')->assertDirectoryEmpty('/wallpapers');
});
<?php
namespace Tests\Feature;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_albums_can_be_uploaded(): void
{
Storage::fake('photos');
$response = $this->json('POST', '/photos', [
UploadedFile::fake()->image('photo1.jpg'),
UploadedFile::fake()->image('photo2.jpg')
]);
// 一つ以上のファイルを保存することをアサート
Storage::disk('photos')->assertExists('photo1.jpg');
Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']);
// ファイルを保存しないことをアサート
Storage::disk('photos')->assertMissing('missing.jpg');
Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']);
// 指定ディレクトリが空であることをアサート
Storage::disk('photos')->assertDirectoryEmpty('/wallpapers');
}
}
fakeメソッドはデフォルトで、テンポラリディレクトリのファイルをすべて削除します。もしこれらのファイルを残しておきたい場合は、代わりに"persistentFake"メソッドを使用してください。ファイルアップロードのテストに関するより詳しい情報は、ファイルアップロードに関するHTTPテストのドキュメントを参照してください。By default, the fake
method will delete all files in its temporary
directory. If you would like to keep these files,
you may use the "persistentFake" method
instead. For more information on testing file
uploads, you may consult the HTTP testing
documentation's information on file
uploads[/docs/{{version}}/http-tests#testing-file-uploads].
Warning!
imageメソッドには、GD拡張が必要です。[!WARNING]
Theimagemethod requires the GD extension[https://www.php.net/manual/en/book.image.php].
カスタムファイルシステムCustom Filesystems
LaravelのFlysystem統合は、最初からすぐに使える「ドライバ」をいくつかサポートしています。ただし、Flysystemはこれらに限定されず、他の多くのストレージシステム用のアダプターを備えています。Laravelアプリケーションでこれらの追加アダプターの1つを使用する場合は、カスタムドライバを作成できます。Laravel's Flysystem integration provides support for several "drivers" out of the box; however, Flysystem is not limited to these and has adapters for many other storage systems. You can create a custom driver if you want to use one of these additional adapters in your Laravel application.
カスタムファイルシステムを定義するには、Flysystemアダプターが必要です。コミュニティが管理するDropboxアダプターをプロジェクトに追加してみましょう。In order to define a custom filesystem you will need a Flysystem adapter. Let's add a community maintained Dropbox adapter to our project:
composer require spatie/flysystem-dropbox
次に、アプリケーションのサービスプロバイダの1つのbootメソッド内にドライバを登録します。これには、Storageファサードのextendメソッドを使用します。Next, you can register the driver
within the boot method of one of your
application's service
providers[/docs/{{version}}/providers]. To
accomplish this, you should use the
extend method of the
Storage facade:
<?php
namespace App\Providers;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use Spatie\Dropbox\Client as DropboxClient;
use Spatie\FlysystemDropbox\DropboxAdapter;
class AppServiceProvider extends ServiceProvider
{
/**
* 全アプリケーションサービスの登録
*/
public function register(): void
{
// ...
}
/**
* 全アプリケーションサービスの初期起動処理
*/
public function boot(): void
{
Storage::extend('dropbox', function (Application $app, array $config) {
$adapter = new DropboxAdapter(new DropboxClient(
$config['authorization_token']
));
return new FilesystemAdapter(
new Filesystem($adapter, $config),
$adapter,
$config
);
});
}
}
extendメソッドの第1引数はドライバ名前で、第2引数は変数$appと$configを受け取るクロージャです。このクロージャはIlluminate\Filesystem\FilesystemAdapterのインスタンスを返さなければなりません。変数$configには、指定したディスクのconfig/filesystems.phpで定義している値が格納されます。The first argument of the
extend method is the name of the driver
and the second is a closure that receives the
$app and $config
variables. The closure must return an instance of
Illuminate\Filesystem\FilesystemAdapter.
The $config variable contains the
values defined in
config/filesystems.php for the
specified disk.
拡張機能のサービスプロバイダを作成・登録したら、config/filesystems.php設定ファイルでdropboxドライバを使用できます。Once you have created and
registered the extension's service provider, you may
use the dropbox driver in your
config/filesystems.php configuration
file.