File storage
- Introduction
- Configuration
- Get disk instance
- Retrieve files Save file
- Delete File
- Directory
- Custom File System
Laravel provides a powerful file system abstraction, which makes Thanks to Frank de Jonge's powerful
Flysystemexpansion pack. Laravel file system integration provides easy-to-use drivers for working with local file systems, Amazon S3, and Rackspace cloud storage. Even better, switching between these storage options is simple since the API remains the same for each system.
The configuration file of the file system is located at
config/filesystems.php. In this file you can configure all "disks". Each disk represents a specific storage drive and storage location. Sample configurations for each supported driver are included in the configuration files. Therefore, just modify the configuration to reflect your storage preferences and credentials. Of course, you can configure multiple disks as needed, and you can even make multiple disks share the same driver.
Public Disk
public
Disk is for files that are to be publicly accessible. By default, the public
disk uses the local
driver and stores these files in the storage/app/public
directory. To make them accessible over the network, you need to create a symbolic link from public/storage
to storage/app/public
. This approach keeps publicly accessible files in the same directory so that they can be easily shared between deployments when using a zero-downtime deployment system such as Envoyer. You can use the Artisan command storage:link
to create a symbolic link:
You can use the Artisan command storage:link
to create a symbolic link:
php artisan storage:link
Of course, once a file is stored and the symlink has been created, you can use the helper function asset
to create the file's URL:
echo asset('storage/file.txt');
Local driver
When using the local
driver, all file operations are related to the root
directory you define in the configuration file. The default value for this directory is storage/app
. Therefore, the following method will store the file in storage/app/file.txt
:
Storage::disk('local')->put('file.txt', 'Contents');##Driver Program prerequisitesComposer packageBefore using drivers such as SFTP, S3 or Rackspace, you need to install the corresponding software package through Composer:
- SFTP:
- league/flysystem-sftp ~1.0
- league/flysystem-aws-s3-v3 ~1.0
- league/flysystem-rackspace ~1.0
- CachedAdapter:
- league/flysystem-cached-adapter ~1.0
config/filesystems.php configuration file. This file contains a sample configuration array for the S3 driver. You are free to modify this array with your own S3 configuration and credentials. For convenience, these environment variables match the naming convention used by the AWS CLI.
filesystems .php file. If necessary, you can use the following sample configuration:
'ftp' => [ 'driver' => 'ftp', 'host' => 'ftp.example.com', 'username' => 'your-username', 'password' => 'your-password', // 可选的 FTP 配置项... // 'port' => 21, // 'root' => '', // 'passive' => true, // 'ssl' => true, // 'timeout' => 30, ],
SFTP driver configuration
Laravel's Flysystem integration package works very well with SFTP; however, there is no sample configuration included in the framework's default configuration file filesystems.php
. If you want to configure an SFTP file system, you can use the following sample configuration:
'sftp' => [ 'driver' => 'sftp', 'host' => 'example.com', 'username' => 'your-username', 'password' => 'your-password', // 基于 SSH 密钥的身份验证设置... // 'privateKey' => '/path/to/privateKey', // 'password' => 'encryption-password', // 可选的 SFTP 配置... // 'port' => 22, // 'root' => '', // 'timeout' => 30, ],
Rackspace drive configuration
Laravel's Flysystem integration package works very well with Rackspace; however, in The framework's default configuration file filesystems.php
does not contain sample configurations. If you want to configure the Rackspace file system, you can use the following example configuration:
'rackspace' => [ 'driver' => 'rackspace', 'username' => 'your-username', 'key' => 'your-key', 'container' => 'your-container', 'endpoint' => 'https://identity.api.rackspacecloud.com/v2.0/', 'region' => 'IAD', 'url_type' => 'publicURL', ],
Cache
Enable caching for the specified disk function, you need to add cache
directly to the configuration items of the disk. The cache
option should be an array of cache configurations, driven by the cache driver name store
(Translator's Note: The original description text of the document disk
is the same as the ## in the example code #store is inconsistent. After verifying the code, it should indeed be
store, so this modification was made.), the expiration time in seconds
expire, and the cache prefix
prefix Composition:
's3' => [ 'driver' => 's3', // 驱动器其他配置... 'cache' => [ 'store' => 'memcached', 'expire' => 600, 'prefix' => 'cache-prefix', ], ],Get disk instance
Storage The facade can be used with any Interact with configured disks. For example, you can use the
put method in the facade to store the avatar to the default disk. If you use any method in the
Storage facade without initially using the
disk method, the called method will automatically be passed to the default disk:
use Illuminate\Support\Facades\Storage; Storage::put('avatars/1', $fileContents);If the application wants to interoperate with multiple disks, you can use the
disk method in the
Storage facade to operate on files on a specific disk:
Storage::disk('s3')->put('avatars/1', $fileContents);Retrieve the file
get method can be used to retrieve the contents of the file. This method returns the original string of the file. content. Remember, all file path specifications should be relative to the "root" directory configured for the disk:
$contents = Storage::get('file.jpg');
exists The method can be used to determine whether the specified file exists on the disk:
$exists = Storage::disk('s3')->exists('file.jpg');
method can be used to generate a response that forces the user's browser to Download the file given the path. download
method accepts a file name as the second parameter of the method, which will determine the file name that the user sees when they download the file. Finally, you can pass an HTTP array header as the third argument to the method: return response()->download('file.jpg');
return response()->download('file.jpg', $name, $headers);
File URLs
You can use the url
method to get the URL of a given file. If you are using the local
driver, generally just add /storage
to the given path and return a relative URL to that file. If you are using the s3
or rackspace
driver, the complete remote URL will be returned:
use Illuminate\Support\Facades\Storage; $url = Storage::url('file.jpg');
{note} Remember, if you are using the
local
driver, all files that want to be publicly accessible should be placed in thestorage/app/public
directory. Additionally you should create a symbolic linkin
public/storage to point to thestorage/app/public
directory.
Temporary URLs
When using the s3
or rackspace
driver to store files, you can use The temporaryUrl
method creates a temporary URL for the given file. This method will receive a path and a DateTime
instance to specify when the URL will expire:
$url = Storage::temporaryUrl( 'file.jpg', now()->addMinutes(5) );
Custom local URL host
If you want to use local
The driver predefines the host for files stored on disk. You can add a url
option to the disk configuration array:
'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', ],
File Metadata
In addition to reading and writing files, Laravel can also provide information about the file itself. For example, the size
method can be used to get the size of the file ( in bytes):
use Illuminate\Support\Facades\Storage; $size = Storage::size('file.jpg');
lastModified
The method returns the UNIX timestamp of the last time the file was modified:
$time = Storage::lastModified('file.jpg');
Save File
put
method can be used to save the original file contents to disk. You can also pass PHP's resource
to the put
method, which will use the underlying stream support under the file system. It is highly recommended to use this method when working with large files:
use Illuminate\Support\Facades\Storage; Storage::put('file.jpg', $contents); Storage::put('file.jpg', $resource);
Automatic Streaming
If you want Laravel to automatically stream a given file to your storage location, you can use the putFile
or putFileAs
method . This method receives an Illuminate\Http\File
or Illuminate\Http\UploadedFile
instance and automatically streams the file to the location you want it to:
use Illuminate\Http\File; use Illuminate\Support\Facades\Storage; // 自动为文件名生成唯一的ID... Storage::putFile('photos', new File('/path/to/photo')); // 手动指定文件名... Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');
Regarding the putFile
method, there are some points to note. We specify a directory name rather than a file name. By default, the putFile
method generates a unique ID as the file name. The file extension is determined based on the MIME type of the detected file. The putFile
method returns the file path so that you can store the file path (including the generated file name) in the database. The
putFile
and putFileAs
methods also accept a method to specify the "visibility" of the stored file. If you store a file on a cloud disk such as S3 and want the file to be publicly accessible, you can use the following function:
Storage::putFile('photos', new File('/path/to/photo'), 'public');
File Data Writing
The prepend
and append
methods allow you to write data at the beginning or end of the file:
Storage::prepend('file.log', 'Prepended Text'); Storage::append('file.log', 'Appended Text');
Copy & Move Files
## The#copy method is used to copy a file to a new location on disk, while the
move method is used to rename or move a file to a new location:
Storage::copy('old/file.jpg', 'new/file.jpg'); Storage::move('old/file.jpg', 'new/file.jpg');File UploadIn web applications, the most commonly used file storage scenario is to upload avatars, photos and files. Laravel's instance method of uploading files
store can easily handle file upload and storage issues. You only need to call the
store method with the file save path as a parameter:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class UserAvatarController extends Controller{ /** * 更新用户头像. * * @param Request $request * @return Response */ public function update(Request $request) { $path = $request->file('avatar')->store('avatars'); return $path; } }There are several points to note in the above example. We specify the directory name, not the file name. By default, the
store method automatically generates a unique ID as the file name. The file's extension will be determined by checking the file's MIME type. The path and file name of the file will be returned by the
store method for subsequent database storage.
putFile method on the
Storage facade to achieve the same effect as the above example:
$path = Storage::putFile('avatars', $request->file('avatar'));Specify FilenameIf you do not want a filename to be automatically assigned to the stored file, you can use the
storeAs method, which accepts a path, filename, and (optionally) disk as its parameters:
$path = $request->file('avatar')->storeAs('avatars', $request->user()->id);You can use the
putFileAs method on the
Storage facade to achieve the same file operation as the above example:
$path = Storage::putFileAs('avatars', $request->file('avatar'), $request->user()->id);
Specify disk
By default, the store
method uses the default disk. If you need to specify another disk, you can pass the disk name as the second parameter of the store
method:
$path = $request->file('avatar')->store('avatars/'.$request->user()->id, 's3');
File Visibility
In the Laravel integrated file system, "visibility" is an abstraction of file permissions on multiple platforms. Files can be declared public
or private
. If a file is declared public
, it means that others can access it. For example, when using the S3 driver, you can retrieve files declared public
.
You can set the visibility of files through the put
method:
use Illuminate\Support\Facades\Storage; Storage::put('file.jpg', $contents, 'public');
getVisibility
and setVisibility
methods can modify existing files Query and set the visibility:
$visibility = Storage::getVisibility('file.jpg'); Storage::setVisibility('file.jpg', 'public')
Delete file
delete
method receives A file name or file name in the form of an array to delete files on the disk:
use Illuminate\Support\Facades\Storage; Storage::delete('file.jpg'); Storage::delete(['file.jpg', 'file2.jpg']);
If necessary, you can specify the disk name to delete the files under it:
use Illuminate\Support\Facades\Storage; Storage::disk('s3')->delete('folder_path/file_name.jpg');
Directory
Get all the files in the directory
files
The method returns the specified directory all files. If you want to retrieve a list of all files in a specified directory (including subdirectories), you can use the allFiles
method:
use Illuminate\Support\Facades\Storage; $files = Storage::files($directory); $files = Storage::allFiles($directory);
Get all directories under the directory
directories
The method returns an array of all directories under the specified directory. In addition, you can use the allDirectories
method to get a list of all directories under a specified directory and its subdirectories:
$directories = Storage::directories($directory); // 递归... $directories = Storage::allDirectories($directory);
Create Directory
The makeDirectory
method will recursively create a directory:
Storage::makeDirectory($directory);
Delete directory
deleteDirectory
The method will delete the specified directory and all files under it:
Storage::deleteDirectory($directory);
Custom file system
Although Laravel's file system provides some out-of-the-box drivers, it is not limited to these and also provides adapters for other file systems. These adapters enable the creation of custom drivers within Lavarel applications.
In order to set up a custom file system, you need a Flysystem adapter. Now let's add the community-maintained Dropbox adapter to the project:
composer require spatie/flysystem-dropbox
Next, you need to create a service provider named DropboxServiceProvider
. In its boot
method, use the extend
method of the Storage
facade to customize the 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{ /** * 执行注册后引导驱动. * * @return void */ public function boot() { Storage::extend('dropbox', function ($app, $config) { $client = new DropboxClient( $config['authorization_token'] ); return new Filesystem(new DropboxAdapter($client)); }); } /** * 在容器中注册绑定. * * @return void */ public function register() { // } }
extend
method The first parameter is the name of the driver, and the second parameter is a closure that accepts $app
and $config
variables. This closure must return an instance of League\Flysystem\Filesystem
. The $config
variable contains the location of the disk in config/filesystems.php
.
Next, register the service provider in the config/app.php
configuration file:
'providers' => [ // ... App\Providers\DropboxServiceProvider::class, ];
After you create and register the service provider, you can pass Add the dropbox
driver to the config/filesystems.php
configuration file and use it.