1

在我的 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 不存在。因为它是一个集合而不是一个媒体模型。

4

2 回答 2

1

查看 Laravel Helpers 文档:http ://laravel.com/docs/4.2/helpers

如果你想要一个指向你的资产的链接,你可以这样做:

$download_link = link_to_asset('file/example.png');

如果上述方法对你不起作用,那么你可以在app/routes.php中实现一个相当简单的下载路由,如下所示:

请注意,此示例假定您的文件位于app/storage/file/位置

// Download Route
Route::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-Za-z(字母)、0-9(数字)-_.(符号)的文件。其他所有内容都被丢弃/忽略。这是一项安全/安保措施....

于 2019-08-15T15:09:28.260 回答
0

All I had to do to get the Media model was changing the following

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

to

$mediaItem = $mediaCollection->where('id', $mediaItemId)->first();
于 2019-08-16T07:22:30.070 回答