首頁 >後端開發 >php教程 >在Laravel中發現文件下載的存儲::下載

在Laravel中發現文件下載的存儲::下載

James Robert Taylor
James Robert Taylor原創
2025-03-06 02:22:091020瀏覽

Discover File Downloads in Laravel with Storage::download

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn