如何将 S3 存储桶中的文件作为 Laravel 中的图像返回?

问题描述

我开始在我的 Laravel 8.x 项目中使用 S3 存储桶,并使用以下代码解决了将文件上传到存储桶的问题:

Storage::disk('s3')->put($file_path_on_s3_drive,$file_content_as_binary);

现在我尝试像这样将这个图像提供给浏览器:

public function showImage(string $id) {
    $image = Image::find($id);

    return Storage::disk('s3')->get($image->file_path_on_s3_drive);
}

但它在浏览器中将文件显示为字符串,而不是图像。

如何在浏览器中将数据显示为图像?

更新: 我从网络路由调用showImage() 函数

Route::get('image/{id}',[ImageController::class,'showImage']);

解决方法

灵魂是:

return response()->make(
    Storage::disk('s3')->get($path_and_filename),200,['Content-Type' => 'image/jpeg']
);