如何使用Laravel从数据库存储和检索图像内容

Shw*_*eta 4 php laravel

我必须存储和检索数据库中的图像。我要存储图像而不是图像路径或图像名称。当我搜索它时,我仅找到用于存储图像路径或名称的解决方案。那么有人可以告诉我如何从数据库中存储和检索大小为KB的图像吗?

这是我的路线。

Route::get('big_image/{id}/image', function ($id)
{
   $user = big_image::find($id);
   return response()->make($user->image, 200, array(
   'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->image)
));
Run Code Online (Sandbox Code Playgroud)

});

这是我的控制器

 public  function new_store(Request $request ,$id){
    $event_id = $id;
    $img = new big_image;
    $file =  $request->file('image');
    $contents = $file->openFile()->fread($file->getSize());
    $img = big_image::find($id);
    $img->image = $contents;
    $img->image_name = $request->image_name;
    $img->event_id = $event_id;
    $img->save();
  $images=DB::table('big_image')->where('event_id','=',$event_id)->get();
  return view('image_upload',compact('images','id','response'));
}
Run Code Online (Sandbox Code Playgroud)

我的display.blade.php文件

@extends('app')
@section('content')
  <h2 style="text-align: center;margin-top: 10px;">Image Gallery</h2>
  <a href="{{url('pic_upload/'.$id.'')}}" class="col-sm-12"             style="padding-left: 0;"><span> add more pictures</span></a><br>
  <a href="{{url('events')}}"><span>Back to events</span></a><br>
   @foreach($images as $item)
    <div class="col-sm-4">
    {{--<img src="data:image/jpeg;base64,'.base64_encode( $item->image  ).'"/>;--}}
    </div>
@endforeach
@stop
Run Code Online (Sandbox Code Playgroud)

Bog*_*dan 8

实际上,对于Laravel,它只涉及几行代码。假设您有一个具有化身的用户,该化身存储在数据库中。假设您使用的是MySQL,请按照以下步骤从数据库中存储和检索化身:

1.首先,您需要avatarusers表中有一列可以存储二进制数据。根据要允许化身图像的大小,列的数据类型可以是以下之一:

BLOB高达64KB

MEDIUMBLOB高达16MB

LONGBLOB最高4GB

2.要将上传的图像存储在数据库中,您可以执行以下操作:

Route::post('user/{id}', function (Request $request, $id) {
    // Get the file from the request
    $file = $request->file('image');

    // Get the contents of the file
    $contents = $file->openFile()->fread($file->getSize());

    // Store the contents to the database
    $user = App\User::find($id);
    $user->avatar = $contents;
    $user->save();
});
Run Code Online (Sandbox Code Playgroud)

3.要获取并输出化身,您可以执行以下操作:

Route::get('user/{id}/avatar', function ($id) {
    // Find the user
    $user = App\User::find(1);

    // Return the image in the response with the correct MIME type
    return response()->make($user->avatar, 200, array(
        'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->avatar)
    ));
});
Run Code Online (Sandbox Code Playgroud)

因此,要使用id等于来访问用户的头像,10只需使用以下URL:

http://domain.com/user/10/avatar
Run Code Online (Sandbox Code Playgroud)