跳轉至內容

檔案儲存

簡介

得益於 Frank de Jonge 出色的 Flysystem PHP 包,Laravel 提供了一個強大的檔案系統抽象。Laravel 對 Flysystem 的整合提供了簡單的驅動程式,用於處理本地檔案系統、SFTP 和 Amazon S3。更棒的是,在本地開發機器和生產伺服器之間切換這些儲存選項非常簡單,因為每個系統的 API 都是相同的。

配置

Laravel 的檔案系統配置檔案位於 config/filesystems.php。在此檔案中,您可以配置所有的檔案系統“磁碟”。每個磁碟代表特定的儲存驅動程式和儲存位置。配置檔案中包含了每個受支援驅動程式的配置示例,您可以根據自己的儲存偏好和憑據修改配置。

local 驅動程式與執行 Laravel 應用程式的伺服器上本地儲存的檔案互動,而 sftp 儲存驅動程式用於基於 SSH 金鑰的 FTP。s3 驅動程式用於寫入 Amazon 的 S3 雲端儲存服務。

您可以配置任意數量的磁碟,甚至可以擁有使用相同驅動程式的多個磁碟。

本地驅動

使用 local 驅動程式時,所有檔案操作都相對於您 filesystems 配置檔案中定義的 root 目錄。預設情況下,此值設定為 storage/app/private 目錄。因此,以下方法會將檔案寫入 storage/app/private/example.txt

1use Illuminate\Support\Facades\Storage;
2 
3Storage::disk('local')->put('example.txt', 'Contents');

公共磁碟

您的應用程式 filesystems 配置檔案中包含的 public 磁碟旨在存放可公開訪問的檔案。預設情況下,public 磁碟使用 local 驅動程式,並將檔案儲存在 storage/app/public 中。

如果您的 public 磁碟使用 local 驅動程式,並且您希望從 Web 訪問這些檔案,則應建立從源目錄 storage/app/public 到目標目錄 public/storage 的符號連結。

要建立符號連結,可以使用 storage:link Artisan 命令。

1php artisan storage:link

一旦檔案被儲存並且符號連結建立完成,您可以使用 asset 輔助函式建立指向這些檔案的 URL。

1echo asset('storage/file.txt');

您可以在 filesystems 配置檔案中配置額外的符號連結。執行 storage:link 命令時,每個配置的連結都將被建立。

1'links' => [
2 public_path('storage') => storage_path('app/public'),
3 public_path('images') => storage_path('app/images'),
4],

storage:unlink 命令可用於刪除已配置的符號連結。

1php artisan storage:unlink

驅動前提條件

S3 驅動配置

在使用 S3 驅動程式之前,您需要透過 Composer 包管理器安裝 Flysystem S3 包。

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

S3 磁碟配置陣列位於您的 config/filesystems.php 配置檔案中。通常,您應該使用 config/filesystems.php 配置檔案引用的以下環境變數來配置您的 S3 資訊和憑據。

1AWS_ACCESS_KEY_ID=<your-key-id>
2AWS_SECRET_ACCESS_KEY=<your-secret-access-key>
3AWS_DEFAULT_REGION=us-east-1
4AWS_BUCKET=<your-bucket-name>
5AWS_USE_PATH_STYLE_ENDPOINT=false

為方便起見,這些環境變數與 AWS CLI 使用的命名約定相匹配。

FTP 驅動配置

在使用 FTP 驅動程式之前,您需要透過 Composer 包管理器安裝 Flysystem FTP 包。

1composer require league/flysystem-ftp "^3.0"

Laravel 的 Flysystem 整合可以很好地與 FTP 配合使用;但是,框架預設的 config/filesystems.php 配置檔案中未包含示例配置。如果您需要配置 FTP 檔案系統,可以使用下面的配置示例。

1'ftp' => [
2 'driver' => 'ftp',
3 'host' => env('FTP_HOST'),
4 'username' => env('FTP_USERNAME'),
5 'password' => env('FTP_PASSWORD'),
6 
7 // Optional FTP Settings...
8 // 'port' => env('FTP_PORT', 21),
9 // 'root' => env('FTP_ROOT'),
10 // 'passive' => true,
11 // 'ssl' => true,
12 // 'timeout' => 30,
13],

SFTP 驅動配置

在使用 SFTP 驅動程式之前,您需要透過 Composer 包管理器安裝 Flysystem SFTP 包。

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

Laravel 的 Flysystem 整合可以很好地與 SFTP 配合使用;但是,框架預設的 config/filesystems.php 配置檔案中未包含示例配置。如果您需要配置 SFTP 檔案系統,可以使用下面的配置示例。

1'sftp' => [
2 'driver' => 'sftp',
3 'host' => env('SFTP_HOST'),
4 
5 // Settings for basic authentication...
6 'username' => env('SFTP_USERNAME'),
7 'password' => env('SFTP_PASSWORD'),
8 
9 // Settings for SSH key-based authentication with encryption password...
10 'privateKey' => env('SFTP_PRIVATE_KEY'),
11 'passphrase' => env('SFTP_PASSPHRASE'),
12 
13 // Settings for file / directory permissions...
14 'visibility' => 'private', // `private` = 0600, `public` = 0644
15 'directory_visibility' => 'private', // `private` = 0700, `public` = 0755
16 
17 // Optional SFTP Settings...
18 // 'hostFingerprint' => env('SFTP_HOST_FINGERPRINT'),
19 // 'maxTries' => 4,
20 // 'passphrase' => env('SFTP_PASSPHRASE'),
21 // 'port' => env('SFTP_PORT', 22),
22 // 'root' => env('SFTP_ROOT', ''),
23 // 'timeout' => 30,
24 // 'useAgent' => true,
25],

作用域與只讀檔案系統

作用域(Scoped)磁碟允許您定義一個檔案系統,其中所有路徑都會自動新增給定的路徑字首。在建立作用域檔案系統磁碟之前,您需要透過 Composer 包管理器安裝額外的 Flysystem 包。

1composer require league/flysystem-path-prefixing "^3.0"

您可以透過定義一個使用 scoped 驅動程式的磁碟,為任何現有的檔案系統磁碟建立路徑作用域例項。例如,您可以建立一個將現有 s3 磁碟作用域限定為特定路徑字首的磁碟,然後每次使用該作用域磁碟進行檔案操作時,都會使用指定的字首。

1's3-videos' => [
2 'driver' => 'scoped',
3 'disk' => 's3',
4 'prefix' => 'path/to/videos',
5],

“只讀”磁碟允許您建立不允許寫入操作的檔案系統磁碟。在使用 read-only 配置選項之前,您需要透過 Composer 包管理器安裝額外的 Flysystem 包。

1composer require league/flysystem-read-only "^3.0"

接下來,您可以在一個或多個磁碟的配置陣列中包含 read-only 配置選項。

1's3-videos' => [
2 'driver' => 's3',
3 // ...
4 'read-only' => true,
5],

相容 Amazon S3 的檔案系統

預設情況下,您的應用程式 filesystems 配置檔案包含一個 s3 磁碟配置。除了使用此磁碟與 Amazon S3 互動外,您還可以將其用於與任何相容 S3 的檔案儲存服務互動,例如 RustFSDigitalOcean SpacesVultr Object StorageCloudflare R2Hetzner Cloud Storage

通常,在更新磁碟憑據以匹配您計劃使用的服務憑據後,您只需要更新 endpoint 配置選項的值。此選項的值通常透過 AWS_ENDPOINT 環境變數定義。

1'endpoint' => env('AWS_ENDPOINT', 'https://rustfs:9000'),

獲取磁碟例項

Storage 外觀(Facade)可用於與您的任何已配置磁碟互動。例如,您可以在外觀上使用 put 方法將頭像儲存在預設磁碟上。如果您在未先呼叫 disk 方法的情況下呼叫 Storage 外觀上的方法,則該方法將自動傳遞到預設磁碟。

1use Illuminate\Support\Facades\Storage;
2 
3Storage::put('avatars/1', $content);

如果您的應用程式與多個磁碟互動,您可以使用 Storage 外觀上的 disk 方法來處理特定磁碟上的檔案。

1Storage::disk('s3')->put('avatars/1', $content);

按需磁碟

有時您可能希望在執行時使用給定的配置建立磁碟,而該配置實際上並不存在於應用程式的 filesystems 配置檔案中。為此,您可以將配置陣列傳遞給 Storage 外觀的 build 方法。

1use Illuminate\Support\Facades\Storage;
2 
3$disk = Storage::build([
4 'driver' => 'local',
5 'root' => '/path/to/root',
6]);
7 
8$disk->put('image.jpg', $content);

讀取檔案

get 方法可用於檢索檔案的內容。該方法將返回檔案的原始字串內容。請記住,所有檔案路徑都應指定為相對於磁碟“根”位置的路徑。

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

如果您要檢索的檔案包含 JSON,則可以使用 json 方法來檢索檔案並解碼其內容。

1$orders = Storage::json('orders.json');

exists 方法可用於確定檔案是否存在於磁碟上。

1if (Storage::disk('s3')->exists('file.jpg')) {
2 // ...
3}

missing 方法可用於確定檔案是否在磁碟上缺失。

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

下載檔案

download 方法可用於生成一個強制使用者瀏覽器下載給定路徑檔案的響應。download 方法接受一個檔名作為第二個引數,這將決定使用者下載檔案時看到的檔名。最後,您可以將 HTTP 標頭陣列作為第三個引數傳遞給該方法。

1return Storage::download('file.jpg');
2 
3return Storage::download('file.jpg', $name, $headers);

檔案 URL

您可以使用 url 方法獲取給定檔案的 URL。如果您使用的是 local 驅動程式,這通常只是在給定路徑前新增 /storage 並返回檔案的相對 URL。如果您使用的是 s3 驅動程式,則將返回完全限定的遠端 URL。

1use Illuminate\Support\Facades\Storage;
2 
3$url = Storage::url('file.jpg');

使用 local 驅動程式時,所有應公開訪問的檔案都應放置在 storage/app/public 目錄中。此外,您應該在 public/storage建立一個符號連結,指向 storage/app/public 目錄。

使用 local 驅動程式時,url 的返回值不會進行 URL 編碼。因此,我們建議始終使用能夠建立有效 URL 的名稱來儲存您的檔案。

URL 主機自定義

如果您想修改使用 Storage 外觀生成的 URL 的主機,可以在磁碟的配置陣列中新增或更改 url 選項。

1'public' => [
2 'driver' => 'local',
3 'root' => storage_path('app/public'),
4 'url' => env('APP_URL').'/storage',
5 'visibility' => 'public',
6 'throw' => false,
7],

臨時 URL

使用 temporaryUrl 方法,您可以為使用 locals3 驅動程式儲存的檔案建立臨時 URL。此方法接受一個路徑和一個指定 URL 何時過期的 DateTime 例項。

1use Illuminate\Support\Facades\Storage;
2 
3$url = Storage::temporaryUrl(
4 'file.jpg', now()->plus(minutes: 5)
5);

啟用本地臨時 URL

如果您在 local 驅動程式引入對臨時 URL 的支援之前就開始開發應用程式,則可能需要啟用本地臨時 URL。為此,請在 config/filesystems.php 配置檔案中將 serve 選項新增到 local 磁碟的配置陣列中。

1'local' => [
2 'driver' => 'local',
3 'root' => storage_path('app/private'),
4 'serve' => true,
5 'throw' => false,
6],

S3 請求引數

如果您需要指定額外的 S3 請求引數,您可以將請求引數陣列作為第三個引數傳遞給 temporaryUrl 方法。

1$url = Storage::temporaryUrl(
2 'file.jpg',
3 now()->plus(minutes: 5),
4 [
5 'ResponseContentType' => 'application/octet-stream',
6 'ResponseContentDisposition' => 'attachment; filename=file2.jpg',
7 ]
8);

自定義臨時 URL

如果您需要自定義特定儲存磁碟如何建立臨時 URL,可以使用 buildTemporaryUrlsUsing 方法。例如,如果您有一個控制器允許您下載透過通常不支援臨時 URL 的磁碟儲存的檔案,這將非常有用。通常,此方法應在服務提供者的 boot 方法中呼叫。

1<?php
2 
3namespace App\Providers;
4 
5use DateTime;
6use Illuminate\Support\Facades\Storage;
7use Illuminate\Support\Facades\URL;
8use Illuminate\Support\ServiceProvider;
9 
10class AppServiceProvider extends ServiceProvider
11{
12 /**
13 * Bootstrap any application services.
14 */
15 public function boot(): void
16 {
17 Storage::disk('local')->buildTemporaryUrlsUsing(
18 function (string $path, DateTime $expiration, array $options) {
19 return URL::temporarySignedRoute(
20 'files.download',
21 $expiration,
22 array_merge($options, ['path' => $path])
23 );
24 }
25 );
26 }
27}

臨時上傳 URL

生成臨時上傳 URL 的能力僅受 s3local 驅動程式支援。

如果您需要生成一個可用於直接從客戶端應用程式上傳檔案的臨時 URL,可以使用 temporaryUploadUrl 方法。此方法接受一個路徑和一個指定 URL 何時過期的 DateTime 例項。temporaryUploadUrl 方法返回一個關聯陣列,該陣列可以解構為上傳 URL 和上傳請求中應包含的標頭。

1use Illuminate\Support\Facades\Storage;
2 
3['url' => $url, 'headers' => $headers] = Storage::temporaryUploadUrl(
4 'file.jpg', now()->plus(minutes: 5)
5);

此方法主要用於需要客戶端應用程式直接將檔案上傳到 Amazon S3 等雲端儲存系統的無伺服器環境。

檔案元資料

除了讀取和寫入檔案外,Laravel 還可以提供有關檔案本身的資訊。例如,size 方法可用於獲取檔案的位元組大小。

1use Illuminate\Support\Facades\Storage;
2 
3$size = Storage::size('file.jpg');

lastModified 方法返回檔案上次被修改時的 UNIX 時間戳。

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

給定檔案的 MIME 型別可以透過 mimeType 方法獲取。

1$mime = Storage::mimeType('file.jpg');

檔案路徑

您可以使用 path 方法獲取給定檔案的路徑。如果您使用的是 local 驅動程式,這將返回檔案的絕對路徑。如果您使用的是 s3 驅動程式,該方法將返回 S3 儲存桶中檔案的相對路徑。

1use Illuminate\Support\Facades\Storage;
2 
3$path = Storage::path('file.jpg');

儲存檔案

put 方法可用於將檔案內容儲存在磁碟上。您也可以將 PHP resource 傳遞給 put 方法,它將使用 Flysystem 底層的流支援。請記住,所有檔案路徑都應指定為相對於為磁碟配置的“根”位置的路徑。

1use Illuminate\Support\Facades\Storage;
2 
3Storage::put('file.jpg', $contents);
4 
5Storage::put('file.jpg', $resource);

寫入失敗

如果 put 方法(或其他“寫入”操作)無法將檔案寫入磁碟,則將返回 false

1if (! Storage::put('file.jpg', $contents)) {
2 // The file could not be written to disk...
3}

如果您願意,可以在檔案系統磁碟的配置陣列中定義 throw 選項。當此選項定義為 true 時,當寫入操作失敗時,put 等“寫入”方法將丟擲 League\Flysystem\UnableToWriteFile 的例項。

1'public' => [
2 'driver' => 'local',
3 // ...
4 'throw' => true,
5],

向檔案前追加和後追加內容

prependappend 方法允許您寫入檔案的開頭或結尾。

1Storage::prepend('file.log', 'Prepended Text');
2 
3Storage::append('file.log', 'Appended Text');

複製和移動檔案

copy 方法可用於將現有檔案複製到磁碟上的新位置,而 move 方法可用於重新命名現有檔案或將其移動到新位置。

1Storage::copy('old/file.jpg', 'new/file.jpg');
2 
3Storage::move('old/file.jpg', 'new/file.jpg');

自動流式傳輸

將檔案流式傳輸到儲存可以顯著減少記憶體使用量。如果您希望 Laravel 自動管理將給定檔案流式傳輸到您的儲存位置,可以使用 putFileputFileAs 方法。此方法接受 Illuminate\Http\FileIlluminate\Http\UploadedFile 例項,並將自動將檔案流式傳輸到您所需的位置。

1use Illuminate\Http\File;
2use Illuminate\Support\Facades\Storage;
3 
4// Automatically generate a unique ID for filename...
5$path = Storage::putFile('photos', new File('/path/to/photo'));
6 
7// Manually specify a filename...
8$path = Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');

關於 putFile 方法,有幾點需要注意。請注意,我們只指定了目錄名稱,而不是檔名。預設情況下,putFile 方法將生成一個唯一 ID 作為檔名。檔案的副檔名將透過檢查檔案的 MIME 型別來確定。putFile 方法將返回檔案的路徑,以便您可以將路徑(包括生成的檔名)儲存在資料庫中。

putFileputFileAs 方法也接受一個引數來指定儲存檔案的“可見性”。如果您將檔案儲存在 Amazon S3 等雲磁碟上,並且希望該檔案可以透過生成的 URL 公開訪問,這將非常有用。

1Storage::putFile('photos', new File('/path/to/photo'), 'public');

檔案上傳

在 Web 應用程式中,儲存檔案最常見的用例之一是儲存使用者上傳的檔案(如照片和文件)。Laravel 使用上傳檔案例項上的 store 方法可以非常輕鬆地儲存上傳的檔案。呼叫 store 方法並傳入您希望儲存上傳檔案的路徑。

1<?php
2 
3namespace App\Http\Controllers;
4 
5use Illuminate\Http\Request;
6 
7class UserAvatarController extends Controller
8{
9 /**
10 * Update the avatar for the user.
11 */
12 public function update(Request $request): string
13 {
14 $path = $request->file('avatar')->store('avatars');
15 
16 return $path;
17 }
18}

關於此示例,有幾點需要注意。請注意,我們只指定了目錄名稱,而不是檔名。預設情況下,store 方法將生成一個唯一 ID 作為檔名。檔案的副檔名將透過檢查檔案的 MIME 型別來確定。store 方法將返回檔案的路徑,以便您可以將路徑(包括生成的檔名)儲存在資料庫中。

您也可以在 Storage 外觀上呼叫 putFile 方法來執行與上述示例相同的檔案儲存操作。

1$path = Storage::putFile('avatars', $request->file('avatar'));

指定檔名

如果您不希望自動為儲存的檔案分配檔名,可以使用 storeAs 方法,它接收路徑、檔名和(可選)磁碟作為其引數。

1$path = $request->file('avatar')->storeAs(
2 'avatars', $request->user()->id
3);

您也可以在 Storage 外觀上使用 putFileAs 方法,它將執行與上述示例相同的檔案儲存操作。

1$path = Storage::putFileAs(
2 'avatars', $request->file('avatar'), $request->user()->id
3);

不可列印和無效的 unicode 字元將自動從檔案路徑中刪除。因此,您可能希望在將檔案路徑傳遞給 Laravel 的檔案儲存方法之前對其進行清理。檔案路徑使用 League\Flysystem\WhitespacePathNormalizer::normalizePath 方法進行標準化。

指定磁碟

預設情況下,此上傳檔案的 store 方法將使用您的預設磁碟。如果您想指定另一個磁碟,請將磁碟名稱作為第二個引數傳遞給 store 方法。

1$path = $request->file('avatar')->store(
2 'avatars/'.$request->user()->id, 's3'
3);

如果您使用的是 storeAs 方法,則可以將磁碟名稱作為第三個引數傳遞給該方法。

1$path = $request->file('avatar')->storeAs(
2 'avatars',
3 $request->user()->id,
4 's3'
5);

其他上傳檔案資訊

如果您想獲取上傳檔案的原始名稱和副檔名,可以使用 getClientOriginalNamegetClientOriginalExtension 方法。

1$file = $request->file('avatar');
2 
3$name = $file->getClientOriginalName();
4$extension = $file->getClientOriginalExtension();

但是,請記住,getClientOriginalNamegetClientOriginalExtension 方法被認為是不安全的,因為檔名和副檔名可能會被惡意使用者篡改。因此,您通常應該更傾向於使用 hashNameextension 方法來獲取給定檔案上傳的名稱和副檔名。

1$file = $request->file('avatar');
2 
3$name = $file->hashName(); // Generate a unique, random name...
4$extension = $file->extension(); // Determine the file's extension based on the file's MIME type...

檔案可見性

在 Laravel 的 Flysystem 整合中,“可見性”是跨多個平臺的檔案許可權的抽象。檔案可以宣告為 publicprivate。當檔案宣告為 public 時,表示該檔案通常應對其他人可見。例如,使用 S3 驅動程式時,您可以檢索 public 檔案的 URL。

您可以在透過 put 方法寫入檔案時設定可見性。

1use Illuminate\Support\Facades\Storage;
2 
3Storage::put('file.jpg', $contents, 'public');

如果檔案已經儲存,可以透過 getVisibilitysetVisibility 方法檢索和設定其可見性。

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

與上傳檔案互動時,您可以使用 storePubliclystorePubliclyAs 方法將上傳的檔案儲存為 public 可見性。

1$path = $request->file('avatar')->storePublicly('avatars', 's3');
2 
3$path = $request->file('avatar')->storePubliclyAs(
4 'avatars',
5 $request->user()->id,
6 's3'
7);

本地檔案和可見性

使用 local 驅動程式時,public 可見性 轉換為目錄的 0755 許可權和檔案的 0644 許可權。您可以在應用程式的 filesystems 配置檔案中修改許可權對映。

1'local' => [
2 'driver' => 'local',
3 'root' => storage_path('app'),
4 'permissions' => [
5 'file' => [
6 'public' => 0644,
7 'private' => 0600,
8 ],
9 'dir' => [
10 'public' => 0755,
11 'private' => 0700,
12 ],
13 ],
14 'throw' => false,
15],

刪除檔案

delete 方法接受單個檔名或要刪除的檔案陣列。

1use Illuminate\Support\Facades\Storage;
2 
3Storage::delete('file.jpg');
4 
5Storage::delete(['file.jpg', 'file2.jpg']);

如有必要,您可以指定要從中刪除檔案的磁碟。

1use Illuminate\Support\Facades\Storage;
2 
3Storage::disk('s3')->delete('path/file.jpg');

目錄

獲取目錄中的所有檔案

files 方法返回給定目錄中所有檔案的陣列。如果您想檢索給定目錄中包括子目錄在內的所有檔案列表,可以使用 allFiles 方法。

1use Illuminate\Support\Facades\Storage;
2 
3$files = Storage::files($directory);
4 
5$files = Storage::allFiles($directory);

獲取目錄中的所有目錄

directories 方法返回給定目錄中所有目錄的陣列。如果您想檢索給定目錄中包括子目錄在內的所有目錄列表,可以使用 allDirectories 方法。

1$directories = Storage::directories($directory);
2 
3$directories = Storage::allDirectories($directory);

建立目錄

makeDirectory 方法將建立給定的目錄,包括任何需要的子目錄。

1Storage::makeDirectory($directory);

刪除目錄

最後,deleteDirectory 方法可用於刪除目錄及其所有檔案。

1Storage::deleteDirectory($directory);

測試

Storage 外觀的 fake 方法允許您輕鬆生成一個偽磁碟,結合 Illuminate\Http\UploadedFile 類的檔案生成工具,極大地簡化了檔案上傳的測試。例如:

1<?php
2 
3use Illuminate\Http\UploadedFile;
4use Illuminate\Support\Facades\Storage;
5 
6test('albums can be uploaded', function () {
7 Storage::fake('photos');
8 
9 $response = $this->json('POST', '/photos', [
10 UploadedFile::fake()->image('photo1.jpg'),
11 UploadedFile::fake()->image('photo2.jpg')
12 ]);
13 
14 // Assert one or more files were stored...
15 Storage::disk('photos')->assertExists('photo1.jpg');
16 Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']);
17 
18 // Assert one or more files were not stored...
19 Storage::disk('photos')->assertMissing('missing.jpg');
20 Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']);
21 
22 // Assert that the number of files in a given directory matches the expected count...
23 Storage::disk('photos')->assertCount('/wallpapers', 2);
24 
25 // Assert that a given directory is empty...
26 Storage::disk('photos')->assertDirectoryEmpty('/wallpapers');
27});
1<?php
2 
3namespace Tests\Feature;
4 
5use Illuminate\Http\UploadedFile;
6use Illuminate\Support\Facades\Storage;
7use Tests\TestCase;
8 
9class ExampleTest extends TestCase
10{
11 public function test_albums_can_be_uploaded(): void
12 {
13 Storage::fake('photos');
14 
15 $response = $this->json('POST', '/photos', [
16 UploadedFile::fake()->image('photo1.jpg'),
17 UploadedFile::fake()->image('photo2.jpg')
18 ]);
19 
20 // Assert one or more files were stored...
21 Storage::disk('photos')->assertExists('photo1.jpg');
22 Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']);
23 
24 // Assert one or more files were not stored...
25 Storage::disk('photos')->assertMissing('missing.jpg');
26 Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']);
27 
28 // Assert that the number of files in a given directory matches the expected count...
29 Storage::disk('photos')->assertCount('/wallpapers', 2);
30 
31 // Assert that a given directory is empty...
32 Storage::disk('photos')->assertDirectoryEmpty('/wallpapers');
33 }
34}

預設情況下,fake 方法將刪除其臨時目錄中的所有檔案。如果您想保留這些檔案,可以使用“persistentFake”方法。有關測試檔案上傳的更多資訊,您可以查閱 HTTP 測試文件中有關檔案上傳的資訊

image 方法需要 GD 擴充套件

自定義檔案系統

Laravel 的 Flysystem 整合開箱即用地支援多種“驅動程式”;但是,Flysystem 並不侷限於這些,並且為許多其他儲存系統提供了介面卡。如果您想在 Laravel 應用程式中使用這些額外的介面卡之一,可以建立一個自定義驅動程式。

為了定義自定義檔案系統,您需要一個 Flysystem 介面卡。讓我們向專案中新增一個社群維護的 Dropbox 介面卡:

1composer require spatie/flysystem-dropbox

接下來,您可以在應用程式的某個 服務提供者boot 方法中註冊驅動程式。為此,您應該使用 Storage 外觀的 extend 方法。

1<?php
2 
3namespace App\Providers;
4 
5use Illuminate\Contracts\Foundation\Application;
6use Illuminate\Filesystem\FilesystemAdapter;
7use Illuminate\Support\Facades\Storage;
8use Illuminate\Support\ServiceProvider;
9use League\Flysystem\Filesystem;
10use Spatie\Dropbox\Client as DropboxClient;
11use Spatie\FlysystemDropbox\DropboxAdapter;
12 
13class AppServiceProvider extends ServiceProvider
14{
15 /**
16 * Register any application services.
17 */
18 public function register(): void
19 {
20 // ...
21 }
22 
23 /**
24 * Bootstrap any application services.
25 */
26 public function boot(): void
27 {
28 Storage::extend('dropbox', function (Application $app, array $config) {
29 $adapter = new DropboxAdapter(new DropboxClient(
30 $config['authorization_token']
31 ));
32 
33 return new FilesystemAdapter(
34 new Filesystem($adapter, $config),
35 $adapter,
36 $config
37 );
38 });
39 }
40}

extend 方法的第一個引數是驅動程式的名稱,第二個引數是一個閉包,該閉包接收 $app$config 變數。閉包必須返回一個 Illuminate\Filesystem\FilesystemAdapter 例項。$config 變數包含在 config/filesystems.php 中為指定磁碟定義的各項值。

建立並註冊擴充套件的服務提供者後,您就可以在 config/filesystems.php 配置檔案中使用 dropbox 驅動程式了。