Laravel框架的Storage::download
方法提供了一個簡潔的API,用於安全地處理文件下載,同時管理文件存儲的抽象。
以下是一個在示例控制器中使用Storage::download()
的例子:
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Storage; class FileController extends Controller { public function download($filename) { return Storage::download( "documents/{$filename}", "custom-{$filename}", ['Content-Type' => 'application/pdf'] ); } }
另一個更複雜的例子,它結合了授權和文件不存在的處理:
<?php namespace App\Http\Controllers; use App\Models\Document; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; class DocumentController extends Controller { public function download(Request $request, Document $document) { if (!$request->user()->canDownload($document)) { abort(403); } if (!Storage::exists($document->path)) { abort(404, 'File not found'); } $document->increment('download_count'); return Storage::download( $document->path, $document->original_name, [ 'Content-Type' => $document->mime_type, 'Content-Disposition' => 'attachment', 'Cache-Control' => 'no-cache, must-revalidate' ] ); } }
總而言之,Storage::download
提供了一種安全高效的文件服務方式,同時隱藏了底層存儲提供商的細節。
以上是在Laravel中發現文件下載的存儲::下載的詳細內容。更多資訊請關注PHP中文網其他相關文章!