我必须从数据库中存储和检索图像。
我想存储图像而不是图像路径或图像名称。当我搜索它时,我只找到了存储图像路径或名称的解决方案。那么有人可以告诉我如何从数据库中存储和检索大小为 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)
));
});
这是我的控制器
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'));
}
我的 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
实际上,Laravel 只需要几行代码。假设您有一个用户,该用户的头像存储在数据库中。假设您使用 MySQL,以下是从数据库存储和检索头像的方法:
1.首先你需要有一个avatar
栏目中的users
可以存储二进制数据的表。根据您想要允许头像图像的大小,列的数据类型可以是以下之一:
BLOB最大 64KB
中型斑点高达 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();
});
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)
));
});
因此,要访问用户的头像id
等于10
你可以只使用这个网址:
http://domain.com/user/10/avatar
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)