file store
brief introduction
Larave PHP package developed based on Frank de Jong Flysystem Provides a powerful file system abstraction layer. Larave integrates Flysystem to simplify the operation of file system with different drivers, including local file system, Amazon S3 and Rackspace cloud storage. In addition, switching between these storage options is very simple, because the API is consistent for different systems.
to configure
The file system configuration file is located in config/filesystems.php
。 All "disks" can be configured in this file. Each disk describes a specific storage drive and storage path. The configuration file provides sample configurations for each supported driver, so simply edit the configuration to apply your storage parameters and authentication information:
'disks' => [ 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), ], 'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/ storage', 'visibility' => 'public', ], 's3' => [ 'driver' => 's3', 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), 'region' => env('AWS_DEFAULT_REGION'), 'bucket' => env('AWS_BUCKET'), 'url' => env('AWS_URL'), ], ],
Of course, you can configure as many disks as you want, and multiple disks can share the same drive.
Public disk
public
Disks are used to store files that can be accessed publicly. By default, public
Disk Usage local
Drive and store files in storage/app/public
Directory. To make these files accessible through a Web browser, you need to create a soft link public/storage
point storage/app/public
In this way, the publicly accessed files can be saved in a directory that can be easily shared by different deployment environments. When deploying systems with zero downtime, such as Envoyer It's especially convenient when it is.
To create this soft chain, you can use the Artisan command storage:link
:
php artisan storage:link
When the file is stored and the soft link has been created, auxiliary functions can be used asset
Create a URL to this file:
echo asset('storage/file.txt');
Local drive
use local
When driving, all file operations are defined in the configuration file filesystems
In root
Directory, which is set to storage/app
Directory, so the following method will store the file to storage/app/file.txt
:
Storage::disk('local')->put('file.txt', 'Contents');
jurisdiction
Document visibility public
Configure the default directory permissions as follows 0775
, file permissions are 0664
。 You can use the configuration file filesystems
Edit these permission mappings in:
'local' => [ 'driver' => 'local', 'root' => storage_path('app'), 'permissions' => [ 'file' => [ 'public' => 0664, 'private' => 0600, ], 'dir' => [ 'public' => 0775, 'private' => 0700, ], ], ],
Drive preparatory knowledge
Composer Package
Before using SFTP or Amazon S3 drivers, you need to install the corresponding packages through Composer:
- SFTP:
league/flysystem-sftp ~1.0
- Amazon S3:
league/flysystem-aws-s3-v3 ~1.0
If you want to consider performance, you must use an additional cache adapter:
- CachedAdapter:
league/flysystem-cached-adapter ~1.0
S3 drive configuration
S3 drive configuration information is located in the configuration file config/filesystems.php
, this file contains the sample configuration array of S3 driver. You can edit this array using your S3 configuration and authentication information. For convenience, these environment variables are consistent with the naming convention of AWS CLI.
FTP drive configuration
Larave's Flysystem integration supports FTP operations, but the framework's default configuration file filesystems.php
Sample configuration is not provided. If you need to configure an FTP file system, you can use the following example configuration:
'ftp' => [ 'driver' => 'ftp', 'host' => 'ftp.example.com', 'username' => 'your-username', 'password' => 'your-password', // Optional FTP Settings... // 'port' => 21, // 'root' => '', // 'passive' => true, // 'ssl' => true, // 'timeout' => 30, ],
SFTP drive configuration
Larave's Flysystem integration supports SFTP operations, but the framework's default filesystems.php
The configuration file does not provide a sample configuration for this. If you need to configure the file system configuration for SFTP, you can use the following example configuration:
'sftp' => [ 'driver' => 'sftp', 'host' => 'example.com', 'username' => 'your-username', 'password' => 'your-password', // Settings for SSH key based authentication... // 'privateKey' => '/path/to/privateKey', // 'password' => 'encryption-password', // Optional SFTP Settings... // 'port' => 22, // 'root' => '', // 'timeout' => 30, ],
cache
To enable caching for a given disk, you need to add cache
Command to disk configuration options, cache
The configuration item should be a disk
Name expire
Time in seconds and cache prefix prefix
Array of:
's3' => [ 'driver' => 's3', // Other Disk Options... 'cache' => [ 'store' => 'memcached', 'expire' => 600, 'prefix' => 'cache-prefix', ], ],
Get hard disk instance
We can use Storage
The door can interact with any disk configured above, for example, you can use the put
Method to store the avatar to the default disk. If you call Storage
Method on the facade without calling disk
Method, the called method will be automatically transferred to the default disk:
use Illuminate\Support\Facades\Storage; Storage::put('avatars/1', $fileContents);
When interacting with multiple disks, you can use the Storage
On the facade disk
Method to access a specific disk:
Storage::disk('s3')->put('avatars/1', $fileContents);
get files
get
Method is used to obtain the content of a given file. This method will return the native string content of the file. Note that all file paths are relative to the default root directory of the disk specified in the configuration file:
$contents = Storage::get('file.jpg');
exists
Method is used to determine whether a given file exists on the disk:
$exists = Storage::disk('s3')->exists('file.jpg');
Download files
download
Method can be used to generate a response that forces a user's browser to download a file of a given path. download
Method receives a file name as the second parameter to determine the file name the user sees when downloading. Finally, you can pass an HTTP request header array as the third parameter of this method:
return Storage::download('file.jpg'); return Storage::download('file.jpg', $name, $headers);
File URL
use local
or s3
When driving, you can use url
Method to get the URI of the given file. If you use local
Drive, usually add /storage
, and return the relative URL of the file; If you are using s3
or rackspace
Drive, a complete remote URL will be returned:
use Illuminate\Support\Facades\Storage; $url = Storage::url('file1.jpg');
Note: Remember, if you are using local
Driver. All files that need public access should be stored in storage/app/public
Directory. In addition, you need to create a pointer to storage/app/public
Of the directory Soft link public/storage
。
Temporary URL
For using s3
or rackspace
Drive the file storage system, and you can use temporaryUrl
Method to create a temporary URL to a given file. The method receives a path parameter and specifies when the URL expires DateTime
example:
$url = Storage::temporaryUrl( 'file1.jpg', now()->addMinutes(5) );
If you need to specify additional S3 request parameters , you can pass the request parameter array as temporaryUrl
The third parameter of the method:
$url = Storage::temporaryUrl( 'file.jpg', now()->addMinutes(5), ['ResponseContentType' => 'application/octet-stream'] );
Custom local host URL
If you want to use predefined local
The host where the drive disk stores files can be added url
Options to disk configuration array:
'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/ storage', 'visibility' => 'public', ],
File meta information
In addition to reading and writing files, Larave can also provide information about the file itself. For example, size
Method can be used to return the file size in bytes:
use Illuminate\Support\Facades\Storage; $size = Storage::size('file1.jpg');
lastModified
Method with UNIX timestamp Format return file last modified:
$time = Storage::lastModified('file1.jpg');
Storage file
put
Method can be used to store native file contents to disk. In addition, you can also pass a PHP resource to put
Method, which will use the underlying stream support of Flysystem. It is recommended to use file streams when processing large files:
use Illuminate\Support\Facades\Storage; Storage::put('file.jpg', $contents); Storage::put('file.jpg', $resource);
Automatic file stream
If you want Larave to automatically output the given file stream to the corresponding storage path, you can use putFile
or putFileAs
Method, which receives Illuminate\Http\File
or Illuminate\Http\UploadedFile
Instance, and then automatically save the file stream to the desired path:
use Illuminate\Http\File; use Illuminate\Support\Facades\Storage; //Automatically calculate MD5 value of file name Storage::putFile('photos', new File('/path/to/photo')); //Specify file name manually Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');
Here's something about putFile
The important note of the method is that we only specify the directory name. By default, putFile
Method automatically generates the file name based on the file content. The implementation principle is to perform MD5 hash operation on the file content. putFile
Method returns the file path, including the file name, for storage in the database.
putFile
and putFileAs
The method also receives a parameter that specifies the "visibility" of the stored file, which is useful when you store the file on a cloud storage (such as S3) platform and expect the file to be publicly accessible:
Storage::putFile('photos', new File('/path/to/photo'), 'public');
Add content to the beginning/end of the file
prepend
and append
Method allows you to easily insert content to the beginning/end of the file:
Storage::prepend('file.log', 'Prepended Text'); Storage::append('file.log', 'Appended Text');
Copy&Move Files
copy
Method copies the existing files on the disk from one place to another, and move
Method: Move the existing files on the disk from one place to another:
Storage::copy('old/file1.jpg', 'new/file1.jpg'); Storage::move('old/file1.jpg', 'new/file1.jpg');
File upload
In Web applications, the most common case of storing files is storing files uploaded by users, such as user avatars, photos and documents. Larravel uploads the store
Method makes it easy to store and upload files. You only need to pass in the path where the uploaded file is saved and call store
Method:
<? php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class UserAvatarController extends Controller { /** *Update user profile * * @param Request $request * @return Response * @translator laravelacademy.org */ public function update(Request $request) { $path = $request->file('avatar')->store('avatars'); return $path; } }
Here are some important notes. Here we only specify the directory name, not the file name. By default, store
Method will automatically generate the file name based on the file content, which is implemented by MD5 on the file content. store
Method returns the file path to save the file path and file name in the database.
You can also call Storage
On the facade putFile
Method to perform the same file operation as the above example:
$path = Storage::putFile('avatars', $request->file('avatar'));
specify a filename
If you don't want to automatically generate file names, you can use storeAs
Method, which takes the path, file name, and disk (optional) as parameters:
$path = $request->file('avatar')->storeAs( 'avatars', $request->user()->id );
Of course, you can also use Storage
On the facade putFileAs
Method, which implements the same operation as the above method:
$path = Storage::putFileAs( 'avatars', $request->file('avatar'), $request->user()->id );
Note: The unprintable and invalid Unicode characters contained in the file path will be automatically removed, so you can "purify" the file path before it is passed to the file storage method, for example, by League\Flysystem\Util::normalizePath
Methods Standardize them.
Specify Disk
By default, store
Method will use the default disk. If you want to specify another disk, pass the disk name as store
The second parameter of the method is:
$path = $request->file('avatar')->store( 'avatars/'.$ request->user()->id, 's3' );
Document visibility
In Laravel's Flysystem integration, "visibility" is an abstraction of file permissions on different platforms. Files can be declared as public
or private
, when the file is declared as public
, which means that the file can be accessed by others. For example, when using S3, you can obtain public
The URL of the file.
use put
You can also set the visibility when setting the file by using the method:
use Illuminate\Support\Facades\Storage; Storage::put('file.jpg', $contents, 'public');
If the file has been stored, the visibility can be getVisibility
and setVisibility
Method acquisition and setting:
$visibility = Storage::getVisibility('file.jpg'); Storage::setVisibility('file.jpg', 'public');
Delete File
delete
Method receives a single file name or multiple file arrays and removes them from the disk:
use Illuminate\Support\Facades\Storage; Storage::delete('file.jpg'); Storage::delete(['file1.jpg', 'file2.jpg']);
If necessary, you can specify which disk to delete files from:
use Illuminate\Support\Facades\Storage; Storage::disk('s3')->delete('folder_path/file_name.jpg');
catalog
Get all files in a directory
files
Method returns an array of all files in a given directory. If you want to get a list of all files in a given directory that contain subdirectories, you can use the allFiles
method:
use Illuminate\Support\Facades\Storage; $files = Storage::files($directory); $files = Storage::allFiles($directory);
Get all subdirectories under a directory
directories
Method returns all directory arrays under the given directory. In addition, you can use the allDirectories
Method to obtain all nested subdirectory arrays:
$directories = Storage::directories($directory); //Recursion $directories = Storage::allDirectories($directory);
Create Directory
makeDirectory
Method will create the given directory, including subdirectories (recursive):
Storage::makeDirectory($directory);
Delete directory
last, deleteDirectory
Method is used to remove a directory, including all files under the directory:
Storage::deleteDirectory($directory);
Custom File System
Larvel's Flysystem integration provides multiple "drivers" out of the box. However, Flysystem does not stop there. It also provides adapters for many other storage systems. By using these additional adapters, you can create custom drivers in your Larravel application.
To set a custom file system, you need a Flysystem adapter. Let's add a community maintained Dropbox adapter to the project:
composer require spatie/flysystem-dropbox
Next, you need to create a Service Provider as DropboxServiceProvider
。 In the provider's boot
Method, you can use Storage
Facade extend
Method definition custom driver:
<? php namespace App\Providers; use Storage; use League\Flysystem\Filesystem; use Illuminate\Support\ServiceProvider; use Spatie\Dropbox\Client as DropboxClient; use Spatie\FlysystemDropbox\DropboxAdapter; class DropboxServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { Storage::extend('dropbox', function ($app, $config) { $client = new DropboxClient( $config['authorizationToken'] ); return new Filesystem(new DropboxAdapter($client)); }); } /** * Register bindings in the container. * * @return void */ public function register() { // } }
extend
The first parameter of the method is the driver name, and the second parameter is to obtain $app
and $config
The closure of the variable. The parser closure must return a League\Flysystem\Filesystem
example. $config
The variable contains the definition in the configuration file config/filesystems.php
Options defined for a specific disk in.
Next, in the configuration file config/app.php
Registered service provider in:
'providers' => [ // ... App\Providers\DropboxServiceProvider::class, ];
After creating and registering the extended service provider, you can use the configuration file config/filesystem.php
In dropbox
Driven.