Laravel framework's Storage::download
method provides a concise API for safely handling file downloads while managing abstractions of file storage.
The following is an example of using Storage::download()
in the example controller:
<?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'] ); } }
Another more complex example, which combines the processing of authorization and non-existence of the file:
<?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' ] ); } }
All in all, Storage::download
provides a safe and efficient way to service files while hiding the details of the underlying storage provider.
The above is the detailed content of Discover File Downloads in Laravel with Storage::download. For more information, please follow other related articles on the PHP Chinese website!