postgresql 如何将Postgres中的blob作为Laravel中的文件提供?

rxztt3cl  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(125)

我的数据库中有以下简单的文件表:

Schema::create('image', function (Blueprint $table) {
    $table->uuid('id')->primary()->default(DB::raw('gen_random_uuid()'));
    $table->binary('image');
    $table->timestamps();
});

在我的控制器中,我有以下内容:

public function getImage(Image $img): Response 
{
    return response($img->image, 200, [
        "Content-Type" => "image/jpeg"
    ]);
}

在我的路线中,我有:

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

响应具有正确的Content-Type,但主体完全为空。我如何在Laravel中通过HTTP将Postgres中的blob作为文件提供?

yyhrrdl8

yyhrrdl81#

当在Laravel中访问Postgres数据库上的二进制列时,访问器返回一个resource,而不是可以在响应中发送到浏览器的原始数据。为了获得这些数据,您可以在资源上使用stream_get_contents()。但是,正如this previous questionlaravel/framework#10847中所指出的,您可能还需要进行额外的编码/解码。
最简单的解决方案是在模型中使用jbernavaprah/eloquent-binary-cast来处理这个问题,方法如下:
1.通过运行composer require jbernavaprah/eloquent-binary-cast将包添加到项目中
1.将'image' => \JBernavaPrah\EloquentBinaryCast\BinaryCast::class,添加到模型的$casts属性

相关问题