通过 ID 获取媒体模型并使用它来制作可下载的 URL 不起作用

在我的 CustomProduct 模型中,我有多个媒体当我发出 GET 请求时,我添加了产品 ID 和媒体 ID。


当我尝试下面的代码时,这是一个雄辩的集合。但我需要它是一个媒体模型,因为我现在不能调用 ->getPath()。


public function downloadMedia($customProduct, $mediaItemId) {

    $product = CustomProduct::find($customProduct);

    $mediaCollection = $product->getMedia('notes');


    $mediaItem = $mediaCollection->where('id', $mediaItemId);


    return response()->download($mediaItem->getPath(), $mediaItem->file_name);

}

预期:我重定向到页面并打开下载的文件模型


实际结果:方法 Illuminate\Database\Eloquent\Collection::getPath 不存在。因为它是一个集合而不是一个媒体模型。


慕容3067478
浏览 162回答 2
2回答

阿晨1998

看看 Laravel Helpers 文档:http ://laravel.com/docs/4.2/helpers如果您想要链接到您的资产,您可以这样做:$download_link = link_to_asset('file/example.png');如果上述方法对您不起作用,那么您可以在app/routes.php 中实现一个相当简单的下载路由,如下所示:请注意,此示例假设您的文件位于app/storage/file/位置// Download RouteRoute::get('download/{filename}', function($filename){    // Check if file exists in app/storage/file folder    $file_path = storage_path() .'/file/'. $filename;    if (file_exists($file_path))    {        // Send Download        return Response::download($file_path, $filename, [            'Content-Length: '. filesize($file_path)        ]);    }    else    {        // Error        exit('Requested file does not exist on our server!');    }})->where('filename', '[A-Za-z0-9\-\_\.]+');用法:http: //your-domain.com/download/example.png这将在以下位置查找文件:app/storage/file/example.png(如果存在,将文件发送到浏览器/客户端,否则将显示错误消息)。PS'[A-Za-z0-9\-\_\.]+此正则表达式确保用户只能请求名称包含 A-Z或a-z(字母)、0-9(数字)-或_或.(符号)的文件。其他所有内容都被丢弃/忽略。这是一项安全/安保措施......

沧海一幻觉

为了获得 Media 模型,我所要做的就是更改以下内容$mediaItem = $mediaCollection->where('id', $mediaItemId);到$mediaItem = $mediaCollection->where('id', $mediaItemId)->first();
打开App,查看更多内容
随时随地看视频慕课网APP