在 Laravel 中提供 PHP 图像资源作为响应



我正在开发一个Web应用程序。在我的应用程序中,我需要处理一些图像并将其显示在浏览器上。但是我没有将图像另存为文件并从路径访问文件。出于某种原因,我没有这样做。相反,我正在从某种字节数据创建一个图像资源,然后提供它。

这是我在控制器中的代码。

function serveS3Image(Request $request)
{
    $image_data = Storage::disk('s3')->get($request->get('identifier'));
    $data = imagecreatefromstring($image_data);
    header('Content-Type: image/png');
    imagepng($data);
}

当我从浏览器访问该操作时,它向我显示正确的图像。但我想以更多的Laravel方式做到这一点。像这样:

function serveS3Image()
{
     return Response::ImageResource($data);
}

如何返回 PHP 镜像资源?

最后,我根据一些答案得到了解决方案。我只需要像这样回来。

return response(Storage::disk('s3')->get($request->get('identifier')))->header('Content-Type', 'image/png');

在响应中,我传递了图像数据,而不是文件路径。然后我在标题中设置内容类型。谢谢伊维。

我在 Laracast 上发现了同样的问题,就像你的一样。看看这个线程。我希望它能对你有所帮助。

编辑:从laracast添加代码

public function downloadAsset($id)
{
    $asset = Asset::find($id);
    $assetPath = Storage::disk('s3')->url($asset->filename);
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=" . basename($assetPath));
    header("Content-Type: " . $asset->mime);
    return readfile($assetPath);
}

https://laravel.com/docs/5.5/responses#file-responses

file 方法可用于直接在用户的浏览器中显示文件,例如图像或 PDF,而不是启动下载。

此方法接受文件的路径作为其第一个参数,接受标头数组作为其第二个参数:

return response()->file($pathToFile);
return response()->file($pathToFile, $headers);

最新更新