Sistema de Archivos / Almacenamiento cloud

Introducción

Laravel provides a powerful filesystem abstraction thanks to the wonderful Flysystem PHP package by Frank de Jonge. La integración de Laravel Flysystem ofrece una forma simple de utilizar drivers para trabajar con sistemas de archivos locales, Amazon S3 y Rackspace Cloud Storage. Even better, it's amazingly simple to switch between these storage options as the API remains the same for each system.

Configuración

El archivo de configuración de filesystem se encuentra en config/filesystems.php. Dentro de este archivo puedes configurar todos tus "disks". Cada disco representa un driver de almacenamiento particular y una ubicación de almacenamiento. Hay configuraciones de ejemplo para cada driver admitido en el archivo de configuración. So, simply modify the configuration to reflect your storage preferences and credentials.

Por supuesto, puedes configurar tantos discos como necesites, pudiendo incluso tener varios discos que utilicen el mismo driver.

The Local Driver

Cuando se utiliza el driver local, ten en cuenta que todas las operaciones de archivo son relativas al directorio root definido en el fichero de configuración. De forma predeterminada, este valor se establece en el directorio storage/app. Por lo tanto, el siguiente método podría guardar un archivo en storage/app/file.txt:

Storage::disk('local')->put('file.txt', 'Contents');

Other Driver Prerequisites

Antes de utilizar los controladores S3 o Rackspace,tendrás que instalar el paquete apropiado vía Composer:

  • Amazon S3: league/flysystem-aws-s3-v3 ~1.0
  • Rackspace: league/flysystem-rackspace ~1.0

Uso básico

Obtaining Disk Instances

La facade Storage se puede utilizar para interactuar con tus discos configurados. 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 call will automatically be passed to the default disk:

<?php

namespace App\Http\Controllers;

use Storage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Update the avatar for the given user.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function updateAvatar(Request $request, $id)
    {
        $user = User::findOrFail($id);

        Storage::put(
            'avatars/'.$user->id,
            file_get_contents($request->file('avatar')->getRealPath())
        );
    }
}

When using multiple disks, you may access a particular disk using the disk method on the Storage facade. Of course, you may continue to chain methods to execute methods on the disk:

$disk = Storage::disk('s3');

$contents = Storage::disk('local')->get('file.jpg')

Retrieving Files

The get method may be used to retrieve the contents of a given file. The raw string contents of the file will be returned by the method:

$contents = Storage::get('file.jpg');

The exists method may be used to determine if a given file exists on the disk:

$exists = Storage::disk('s3')->exists('file.jpg');

File Meta Information

The size method may be used to get the size of the file in bytes:

$size = Storage::size('file1.jpg');

The lastModified method returns the UNIX timestamp of the last time the file was modified:

$time = Storage::lastModified('file1.jpg');

Storing Files

The put method may be used to store a file on disk. You may also pass a PHP resource to the put method, which will use Flysystem's underlying stream support. Using streams is greatly recommended when dealing with large files:

Storage::put('file.jpg', $contents);

Storage::put('file.jpg', $resource);

The copy method may be used to move an existing file to a new location on the disk:

Storage::copy('old/file1.jpg', 'new/file1.jpg');

The move method may be used to move an existing file to a new location:

Storage::move('old/file1.jpg', 'new/file1.jpg');

Prepending / Appending To Files

The prepend and append methods allow you to easily insert content at the beginning or end of a file:

Storage::prepend('file.log', 'Prepended Text');

Storage::append('file.log', 'Appended Text');

Deleting Files

The delete method accepts a single filename or an array of files to remove from the disk:

Storage::delete('file.jpg');

Storage::delete(['file1.jpg', 'file2.jpg']);

Directories

Obtener todos los archivos en un directorio

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 sub-directories, you may use the allFiles method:

$files = Storage::files($directory);

$files = Storage::allFiles($directory);

Obtener todos los directorios dentro de un directorio

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 sub-directories:

$directories = Storage::directories($directory);

// Ejecución recursiva...
$directories = Storage::allDirectories($directory);

Crear un directorio

The makeDirectory method will create the given directory, including any needed sub-directories:

Storage::makeDirectory($directory);

Eliminar un directorio

Finally, the deleteDirectory may be used to remove a directory, including all of its files, from the disk:

Storage::deleteDirectory($directory);

Filesystems personalizados

La integración Flysystem de Laravel provee controladores para varios "drivers"; sin embargo, Flysystem no está limitado a estos y tiene adaptadores para muchos otros sistemas de almacenamiento. Puedes crear tu propio driver si no quieres utilizar ninguno de estos adaptadores adicionales en tu aplicación Laravel.

In order to set up the custom filesystem you will need to create a service provider such as DropboxServiceProvider. In the provider's boot method, you may use the Storage facade's extend method to define the custom driver:

<?php

namespace App\Providers;

use Storage;
use League\Flysystem\Filesystem;
use Dropbox\Client as DropboxClient;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Dropbox\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['accessToken'], $config['clientIdentifier']
            );

            return new Filesystem(new DropboxAdapter($client));
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

El primer argumento del método extend es el nombre del driver y el segundo es un Closure recibe las variables $app y $config. The resolver Closure must return an instance of League\Flysystem\Filesystem. The $config variable contains the values defined in config/filesystems.php for the specified disk.

Once you have created the service provider to register the extension, you may use the dropbox driver in your config/filesystem.php configuration file.