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中文网其他相关文章!