Does a Folder Have to Exist to Upload Into S3
File Storage
- Introduction
- Configuration
- The Local Driver
- The Public Disk
- Driver Prerequisites
- Amazon S3 Compatible Filesystems
- Obtaining Deejay Instances
- On-Demand Disks
- Retrieving Files
- Downloading Files
- File URLs
- File Metadata
- Storing Files
- Prepending & Appending To Files
- Copying & Moving Files
- Automatic Streaming
- File Uploads
- File Visibility
- Deleting Files
- Directories
- Custom Filesystems
Introduction
Laravel provides a powerful filesystem abstraction thank you to the wonderful Flysystem PHP bundle by Frank de Jonge. The Laravel Flysystem integration provides uncomplicated drivers for working with local filesystems, SFTP, and Amazon S3. Even meliorate, information technology'southward amazingly uncomplicated to switch between these storage options betwixt your local development machine and production server as the API remains the same for each arrangement.
Configuration
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 reverberate your storage preferences and credentials.
The local
commuter interacts with files stored locally on the server running the Laravel application while the s3
driver is used to write to Amazon's S3 deject storage service.
{tip} You may configure as many disks as yous like and may even take multiple disks that apply the same driver.
The Local Commuter
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
:
utilize Illuminate\Support\Facades\ Storage ;
Storage :: deejay ( ' local ' ) -> put ( ' example.txt ' , ' Contents ' );
The Public Disk
The public
disk included in your awarding'south filesystems
configuration file is intended for files that are going to be publicly accessible. By default, the public
deejay uses the local
driver and stores its files in storage/app/public
.
To make these files attainable from the web, yous should create a symbolic link from public/storage
to storage/app/public
. Utilizing this folder convention will keep your publicly attainable files in one directory that can be easily shared across deployments when using zero downward-fourth dimension deployment systems like Envoyer.
To create the symbolic link, you may apply the storage:link
Artisan control:
php artisan storage:link
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 ' );
You may configure additional symbolic links in your filesystems
configuration file. Each of the configured links volition exist created when you run the storage:link
command:
' links ' => [
public_path ( ' storage ' ) => storage_path ( ' app/public ' ),
public_path ( ' images ' ) => storage_path ( ' app/images ' ),
],
Commuter Prerequisites
S3 Commuter Configuration
Before using the S3 commuter, you will need to install the Flysystem S3 package via the Composer packet managing director:
composer require -W league/flysystem-aws-s3-v3 " ^3.0 "
The S3 driver configuration data is located in your config/filesystems.php
configuration file. This file contains an example configuration assortment for an S3 driver. Yous are costless to modify this array with your own S3 configuration and credentials. For convenience, these environment variables match the naming convention used past the AWS CLI.
FTP Commuter Configuration
Before using the FTP commuter, you will need to install the Flysystem FTP package via the Composer packet manager:
composer require league/flysystem-ftp " ^3.0 "
Laravel'south Flysystem integrations piece of work keen with FTP; withal, a sample configuration is not included with the framework's default filesystems.php
configuration file. If you need to configure an FTP filesystem, you may use the configuration example beneath:
' ftp ' => [
' driver ' => ' ftp ' ,
' host ' => env ( ' FTP_HOST ' ),
' username ' => env ( ' FTP_USERNAME ' ),
' password ' => env ( ' FTP_PASSWORD ' ),
// Optional FTP Settings...
// 'port' => env('FTP_PORT', 21),
// 'root' => env('FTP_ROOT'),
// 'passive' => true,
// 'ssl' => true,
// 'timeout' => thirty,
],
SFTP Commuter Configuration
Before using the SFTP commuter, y'all will need to install the Flysystem SFTP package via the Composer package manager:
composer require league/flysystem-sftp-v3 " ^iii.0 "
Laravel's Flysystem integrations work great with SFTP; however, a sample configuration is not included with the framework'due south default filesystems.php
configuration file. If yous need to configure an SFTP filesystem, you lot may employ the configuration instance below:
' sftp ' => [
' driver ' => ' sftp ' ,
' host ' => env ( ' SFTP_HOST ' ),
// Settings for basic authentication...
' username ' => env ( ' SFTP_USERNAME ' ),
' password ' => env ( ' SFTP_PASSWORD ' ),
// Settings for SSH key based authentication with encryption password...
' privateKey ' => env ( ' SFTP_PRIVATE_KEY ' ),
' countersign ' => env ( ' SFTP_PASSWORD ' ),
// Optional SFTP Settings...
// 'hostFingerprint' => env('SFTP_HOST_FINGERPRINT'),
// 'maxTries' => 4,
// 'passphrase' => env('SFTP_PASSPHRASE'),
// 'port' => env('SFTP_PORT', 22),
// 'root' => env('SFTP_ROOT', ''),
// 'timeout' => xxx,
// 'useAgent' => true,
],
Amazon S3 Compatible Filesystems
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 employ information technology to interact with any S3 uniform file storage service such as MinIO or DigitalOcean Spaces.
Typically, after updating the deejay'southward credentials to match the credentials of the service you are planning to use, y'all only demand to update the value of the url
configuration pick. This option'southward value is typically defined via the AWS_ENDPOINT
environment variable:
' endpoint ' => env ( ' AWS_ENDPOINT ' , ' https://minio:9000 ' ),
Obtaining Deejay Instances
The Storage
facade may exist used to collaborate with any of your configured disks. For example, you may employ the put
method on the facade to store an avatar on the default disk. If y'all call methods on the Storage
facade without first calling the deejay
method, the method will automatically be passed to the default disk:
utilise Illuminate\Support\Facades\ Storage ;
Storage :: put ( ' avatars/one ' , $content );
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
Sometimes you may wish to create a disk at runtime using a given configuration without that configuration actually being present in your application'south filesystems
configuration file. To accomplish this, yous 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
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 exist specified relative to the disk'south "root" location:
$contents = Storage :: get ( ' file.jpg ' );
The exists
method may exist used to make up one's mind if a file exists on the disk:
if ( Storage :: deejay ( ' s3 ' ) -> exists ( ' file.jpg ' )) {
// ...
}
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
The download
method may exist used to generate a response that forces the user'southward browser to download the file at the given path. The download
method accepts a filename as the second argument to the method, which will make up one's mind the filename that is seen by the user downloading the file. Finally, y'all may pass an array of HTTP headers as the tertiary statement to the method:
return Storage :: download ( ' file.jpg ' );
render Storage :: download ( ' file.jpg ' , $name , $headers );
File URLs
You may apply the url
method to get the URL for a given file. If yous are using the local
commuter, 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 volition be returned:
use Illuminate\Back up\Facades\ Storage ;
$url = Storage :: url ( ' file.jpg ' );
When using the local
driver, all files that should be publicly accessible should be placed in the storage/app/public
directory. Furthermore, you lot should create a symbolic link at public/storage
which points to the storage/app/public
directory.
{notation} When using the
local
commuter, the return value ofurl
is not URL encoded. For this reason, we recommend always storing your files using names that will create valid URLs.
Temporary URLs
Using the temporaryUrl
method, you lot 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:
utilise Illuminate\Support\Facades\ Storage ;
$url = Storage :: temporaryUrl (
' file.jpg ' , now () -> addMinutes ( v )
);
If yous need to specify additional S3 request parameters, you may pass the assortment of request parameters as the tertiary argument to the temporaryUrl
method:
$url = Storage :: temporaryUrl (
' file.jpg ' ,
at present () -> addMinutes ( v ),
[
' ResponseContentType ' => ' application/octet-stream ' ,
' ResponseContentDisposition ' => ' zipper; filename=file2.jpg ' ,
]
);
If you demand to customize how temporary URLs are created for a specific storage disk, yous can use the buildTemporaryUrlsUsing
method. For example, this can exist useful if yous take a controller that allows you to download files stored via a disk that doesn't typically support temporary URLs. Ordinarily, this method should be chosen from the kicking
method of a service provider:
<?php
namespace App\Providers;
utilise Illuminate\Support\Facades\ Storage ;
use Illuminate\Support\Facades\ URL ;
use Illuminate\Support\ ServiceProvider ;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap whatsoever application services.
*
* @return void
*/
public part boot ()
{
Storage :: deejay ( ' local ' ) -> buildTemporaryUrlsUsing ( function ( $path , $expiration , $options ) {
render URL :: temporarySignedRoute (
' files.download ' ,
$expiration ,
array_merge ($ options , [ ' path ' => $ path ])
);
});
}
}
URL Host Customization
If you would like to pre-define the host for URLs generated using the Storage
facade, you may add together a url
option to the disk'due south configuration assortment:
' public ' => [
' driver ' => ' local ' ,
' root ' => storage_path ( ' app/public ' ),
' url ' => env ( ' APP_URL ' ) . ' /storage ' ,
' visibility ' => ' public ' ,
],
File Metadata
In improver to reading and writing files, Laravel can too provide information well-nigh 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 ' );
The lastModified
method returns the UNIX timestamp of the last time the file was modified:
$time = Storage :: lastModified ( ' file.jpg ' );
File Paths
You may use the path
method to get the path for a given file. If you are using the local
driver, this will render the accented path to the file. If y'all are using the s3
driver, this method will return the relative path to the file in the S3 bucket:
apply Illuminate\Support\Facades\ Storage ;
$path = Storage :: path ( ' file.jpg ' );
Storing Files
The put
method may be used to store file contents on a disk. You may besides pass a PHP resource
to the put
method, which will use Flysystem'southward underlying stream support. Remember, all file paths should exist 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
If the put
method (or other "write" operations) is unable to write the file to deejay, fake
volition exist returned:
if ( ! Storage :: put ( ' file.jpg ' , $contents )) {
// The file could not be written to disk...
}
If you wish, you may define the throw
choice within your filesystem disk'southward configuration array. When this option is defined as true
, "write" methods such equally put
will throw an instance of League\Flysystem\UnableToWriteFile
when write operations neglect:
' public ' => [
' commuter ' => ' local ' ,
// ...
' throw ' => true ,
],
Prepending & Appending To Files
The prepend
and append
methods permit you lot to write to the beginning or end of a file:
Storage :: prepend ( ' file.log ' , ' Prepended Text ' );
Storage :: append ( ' file.log ' , ' Appended Text ' );
Copying & Moving Files
The copy
method may exist used to copy an existing file to a new location on the disk, while the movement
method may be used to rename or motion an existing file to a new location:
Storage :: re-create ( ' old/file.jpg ' , ' new/file.jpg ' );
Storage :: move ( ' sometime/file.jpg ' , ' new/file.jpg ' );
Automatic Streaming
Streaming files to storage offers significantly reduced retentiveness usage. If you would similar Laravel to automatically manage streaming a given file to your storage location, you lot may utilise the putFile
or putFileAs
method. This method accepts either an Illuminate\Http\File
or Illuminate\Http\UploadedFile
example and will automatically stream the file to your desired location:
use Illuminate\Http\ File ;
employ Illuminate\Support\Facades\ Storage ;
// Automatically generate a unique ID for filename...
$path = Storage :: putFile ( ' photos ' , new File ( ' /path/to/photo ' ));
// Manually specify a filename...
$path = Storage :: putFileAs ( ' photos ' , new File ( ' /path/to/photo ' ), ' photograph.jpg ' );
There are a few important things to note nigh the putFile
method. Note that we only specified a directory proper name and not a filename. By default, the putFile
method will generate a unique ID to serve equally the filename. The file'due south extension will be determined past examining the file's MIME type. The path to the file volition exist returned by the putFile
method and so yous can shop the path, including the generated filename, in your database.
The putFile
and putFileAs
methods as well accept an statement to specify the "visibility" of the stored file. This is especially useful if y'all are storing the file on a cloud disk such as Amazon S3 and would similar the file to be publicly accessible via generated URLs:
Storage :: putFile ( ' photos ' , new File ( ' /path/to/photo ' ), ' public ' );
File Uploads
In spider 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. Phone call the shop
method with the path at which you wish to store the uploaded file:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\ Controller ;
utilise Illuminate\Http\ Request ;
course UserAvatarController extends Controller
{
/**
* Update the avatar for the user.
*
* @param \ Illuminate \ Http \ Request $request
* @return \ Illuminate \ Http \ Response
*/
public function update ( Request $request )
{
$path = $request -> file ( ' avatar ' ) -> store ( ' avatars ' );
return $path ;
}
}
There are a few important things to note most this example. Note that we only specified a directory proper noun, not a filename. Past default, the shop
method will generate a unique ID to serve as the filename. The file'south extension volition exist determined by examining the file's MIME type. The path to the file will be returned by the store
method so you tin store the path, including the generated filename, in your database.
Yous may also call the putFile
method on the Storage
facade to perform the aforementioned file storage performance as the example to a higher place:
$path = Storage :: putFile ( ' avatars ' , $request -> file ( ' avatar ' ));
Specifying A File Proper noun
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 equally its arguments:
$path = $request -> file ( ' avatar ' ) -> storeAs (
' avatars ' , $request -> user () ->id
);
You may likewise use the putFileAs
method on the Storage
facade, which will perform the aforementioned file storage functioning as the example higher up:
$path = Storage :: putFileAs (
' avatars ' , $request -> file ( ' avatar ' ), $request -> user () ->id
);
{note} Unprintable and invalid unicode characters volition 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 the
League\Flysystem\WhitespacePathNormalizer::normalizePath
method.
Specifying A Deejay
By default, this uploaded file's store
method volition employ your default deejay. If yous would like to specify some other disk, pass the disk proper noun every bit the second argument to the store
method:
$path = $asking -> file ( ' avatar ' ) -> store (
' avatars/ ' . $asking -> user () ->id , ' s3 '
);
If yous are using the storeAs
method, you may pass the disk name every bit the third argument to the method:
$path = $request -> file ( ' avatar ' ) -> storeAs (
' avatars ' ,
$request -> user () ->id ,
' s3 '
);
Other Uploaded File Information
If you would similar to get the original name and extension of the uploaded file, you may do and so using the getClientOriginalName
and getClientOriginalExtension
methods:
$file = $request -> file ( ' avatar ' );
$name = $file -> getClientOriginalName ();
$extension = $file -> getClientOriginalExtension ();
However, keep in heed that the getClientOriginalName
and getClientOriginalExtension
methods are considered unsafe, every bit the file proper 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 (); // Generate a unique, random name...
$extension = $file -> extension (); // Determine the file's extension based on the file'due south MIME blazon...
File Visibility
In Laravel'southward Flysystem integration, "visibility" is an brainchild 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 mostly exist attainable to others. For example, when using the S3 driver, you may remember URLs for public
files.
You tin can set the visibility when writing the file via the put
method:
use Illuminate\Support\Facades\ Storage ;
Storage :: put ( ' file.jpg ' , $contents , ' public ' );
If the file has already been stored, its visibility can be retrieved and gear up via the getVisibility
and setVisibility
methods:
$visibility = Storage :: getVisibility ( ' file.jpg ' );
Storage :: setVisibility ( ' file.jpg ' , ' public ' );
When interacting with uploaded files, yous may employ 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 ' ,
$asking -> user () ->id ,
' s3 '
);
Local Files & Visibility
When using the local
driver, public
visibility translates to 0755
permissions for directories and 0644
permissions for files. You tin can modify the permissions mappings in your application'southward filesystems
configuration file:
' local ' => [
' driver ' => ' local ' ,
' root ' => storage_path ( ' app ' ),
' permissions ' => [
' file ' => [
' public ' => 0644 ,
' private ' => 0600 ,
],
' dir ' => [
' public ' => 0755 ,
' private ' => 0700 ,
],
],
],
Deleting Files
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 exist deleted from:
use Illuminate\Support\Facades\ Storage ;
Storage :: disk ( ' s3 ' ) -> delete ( ' path/file.jpg ' );
Directories
Get All Files Within A Directory
The files
method returns an array of all of the files in a given directory. If you lot would like to recollect a listing of all files within a given directory including all subdirectories, you may apply the allFiles
method:
use Illuminate\Support\Facades\ Storage ;
$files = Storage :: files ( $directory );
$files = Storage :: allFiles ( $directory );
Go All Directories Inside A Directory
The directories
method returns an array of all the directories within a given directory. Additionally, you may use the allDirectories
method to become a listing of all directories inside a given directory and all of its subdirectories:
$directories = Storage :: directories ( $directory );
$directories = Storage :: allDirectories ( $directory );
Create A Directory
The makeDirectory
method volition create the given directory, including any needed subdirectories:
Storage :: makeDirectory ( $directory );
Delete A Directory
Finally, the deleteDirectory
method may be used to remove a directory and all of its files:
Storage :: deleteDirectory ( $directory );
Custom Filesystems
Laravel's Flysystem integration provides support for several "drivers" out of the box; however, Flysystem is not express to these and has adapters for many other storage systems. Y'all can create a custom commuter if you lot want to utilise one of these additional adapters in your Laravel application.
In lodge to define a custom filesystem you volition need a Flysystem adapter. Let's add a community maintained Dropbox adapter to our project:
composer require spatie/flysystem-dropbox
Side by side, you lot can annals the driver within the kicking
method of one of your application's service providers. To accomplish this, yous should use the extend
method of the Storage
facade:
<?php
namespace App\Providers;
use Illuminate\Filesystem\ FilesystemAdapter ;
use Illuminate\Support\Facades\ Storage ;
utilize Illuminate\Support\ ServiceProvider ;
use League\Flysystem\ Filesystem ;
employ Spatie\Dropbox\ Customer as DropboxClient;
utilise Spatie\FlysystemDropbox\ DropboxAdapter ;
grade AppServiceProvider extends ServiceProvider
{
/**
* Register whatsoever application services.
*
* @return void
*/
public function register ()
{
//
}
/**
* Bootstrap any awarding services.
*
* @return void
*/
public role boot ()
{
Storage :: extend ( ' dropbox ' , part ( $app , $config ) {
$adapter = new DropboxAdapter ( new DropboxClient (
$config [ ' authorization_token ' ]
));
return new FilesystemAdapter (
new Filesystem ( $adapter , $config ),
$adapter ,
$config
);
});
}
}
The offset 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 example of Illuminate\Filesystem\FilesystemAdapter
. The $config
variable contains the values defined in config/filesystems.php
for the specified disk.
One time yous have created and registered the extension's service provider, you may use the dropbox
driver in your config/filesystems.php
configuration file.
weberentrught1943.blogspot.com
Source: https://laravel.com/docs/9.x/filesystem
0 Response to "Does a Folder Have to Exist to Upload Into S3"
Post a Comment