首页 > 后端开发 > php教程 > 在Laravel中发现文件下载的存储::下载

在Laravel中发现文件下载的存储::下载

James Robert Taylor
发布: 2025-03-06 02:22:09
原创
1018 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板