Laravel 5.5 - 在没有创建符号链接的情况下访问存储映像 - 抛出 400 错误



routes.php

Route::get('img/{filename}', 'FilesController@show')->name('files.show');

我的文件控制器

public function show($filename)
{
    if (!Storage::exists('img/' . $filename))
    {
        return 'error'; //file exist, this is never executes
    }
    $file = Storage::get('img/' . $filename); // this line breaks
    dd($file);
    return new Response($file, 200);
}

存储::get('img/' . $filename) 在页面上抛出错误 400...路径很好...

我不想要公共链接,因为我希望图像是私有的并且只能通过控制器访问......

首先,必须从控制器操作返回response对象。但是你在if中返回string.

其次,您返回错误的下载响应。浏览器无法理解您的响应,因此您会收到 400 错误。要下载文件,请使用response()->download(...)功能。

问题是我没有在服务器上存储图像内容。

我只是存储没有内容的名称。

以下代码返回图像。

public function show($filename)
{
    $storage = Storage::disk('local');
    if (!$storage->exists($filename)) {
        return 'error';
    }
    $file = $storage->get($filename);
    $type = $storage->mimeType($filename);
    return new Response($file, 200, [
        'Content-Type' => $type
    ]);
}

无论如何,感谢您的帮助:)

最新更新