Skip to content

Lưu trữ tệp tin (File Storage)

Giới thiệu (Introduction)

Laravel cung cấp filesystem abstraction mạnh mẽ nhờ package Flysystem. Tích hợp này cung cấp drivers đơn giản cho local filesystems, SFTP, và Amazon S3 — với API thống nhất cho mọi storage backends.

Cấu hình (Configuration)

File cấu hình tại config/filesystems.php. Mỗi "disk" đại diện cho storage driver và vị trí lưu trữ cụ thể.

Local Driver

Tương tác với files local trên server. Mặc định root là storage/app.

Public Disk

Disk public dành cho files accessible công khai:

bash
php artisan storage:link

Tạo symbolic link từ public/storagestorage/app/public.

Driver Prerequisites

S3

bash
composer require league/flysystem-aws-s3-v3 "^3.0" --with-all-dependencies

SFTP

bash
composer require league/flysystem-sftp-v3 "^3.0"

Scoped & Read-Only Filesystems

Scoped disk giới hạn paths tự động:

php
's3-videos' => [
    'driver' => 'scoped',
    'disk' => 's3',
    'prefix' => 'path/to/videos',
],

Read-only disk:

php
's3-videos' => [
    'driver' => 's3',
    // ...
    'read-only' => true,
],

Lấy Disk Instances

php
use Illuminate\Support\Facades\Storage;

// Disk mặc định
Storage::put('avatars/1', $content);

// Disk cụ thể
Storage::disk('s3')->put('avatars/1', $content);

On-Demand Disks

Tạo disk tại runtime:

php
$disk = Storage::build([
    'driver' => 'local',
    'root' => '/path/to/root',
]);

$disk->put('image.jpg', $content);

Đọc Files (Retrieving Files)

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

// Kiểm tra tồn tại
if (Storage::disk('s3')->exists('file.jpg')) {
    // ...
}

if (Storage::disk('s3')->missing('file.jpg')) {
    // ...
}

Download Files

php
return Storage::download('file.jpg');
return Storage::download('file.jpg', $name, $headers);

File URLs

php
$url = Storage::url('file.jpg');

Temporary URLs (Pre-signed URLs)

Với S3 — tạo URL tạm thời:

php
$url = Storage::temporaryUrl(
    'file.jpg', now()->addMinutes(5)
);

File Metadata

php
$size = Storage::size('file.jpg');
$time = Storage::lastModified('file.jpg');
$mime = Storage::mimeType('file.jpg');
$path = Storage::path('file.jpg'); // Đường dẫn tuyệt đối

Lưu Files (Storing Files)

php
Storage::put('file.jpg', $contents);
Storage::put('file.jpg', $resource); // Từ resource stream

// Tự động streaming cho files lớn
Storage::putFile('photos', new File('/path/to/photo'));
Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');

Prepending & Appending

php
Storage::prepend('file.log', 'Dòng đầu');
Storage::append('file.log', 'Dòng cuối');

Copying & Moving

php
Storage::copy('old/file.jpg', 'new/file.jpg');
Storage::move('old/file.jpg', 'new/file.jpg');

File Uploads

php
$path = $request->file('avatar')->store('avatars');
$path = $request->file('avatar')->storeAs('avatars', 'filename.jpg');

// Chỉ định disk
$path = $request->file('avatar')->store('avatars', 's3');

File Visibility

Với S3, control public/private access:

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

$visibility = Storage::getVisibility('file.jpg');
Storage::setVisibility('file.jpg', 'public');

Xóa Files (Deleting Files)

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

Thư mục (Directories)

php
// Liệt kê files
$files = Storage::files($directory);
$files = Storage::allFiles($directory); // Bao gồm subdirectories

// Liệt kê thư mục
$directories = Storage::directories($directory);
$directories = Storage::allDirectories($directory);

// Tạo thư mục
Storage::makeDirectory($directory);

// Xóa thư mục (và toàn bộ files)
Storage::deleteDirectory($directory);

Testing

php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

Storage::fake('avatars');

// Upload file giả
$file = UploadedFile::fake()->image('avatar.jpg');

// Action...

Storage::disk('avatars')->assertExists('avatar.jpg');
Storage::disk('avatars')->assertMissing('missing.jpg');

Custom Filesystems

Đăng ký custom driver trong AppServiceProvider:

php
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Filesystem;

Storage::extend('dropbox', function (Application $app, array $config) {
    $adapter = new DropboxAdapter(/* ... */);
    return new FilesystemAdapter(
        new Filesystem($adapter, $config),
        $adapter,
        $config
    );
});