首页 > 解决方案 > 在 laravel 中使用 postgres bytea blob 字段上传图片

问题描述

我找不到任何关于如何在 laravel 项目中使用 bytea 在 postgres 中存储和检索图像的文章。我特别关注使用 ajax 调用保存和检索数据。

标签: phplaravelpostgresqlbytea

解决方案


public function store(Request $request)
    {
        $this->validate($request,[
            'title' =>'required',
            'image' => 'mimes:jpeg,jpg,bmp,png',

        ]);



          $image = $request->file('image');
        $slug = str_slug($request->title);
        if (isset($image))
        {
            $currentDate = Carbon::now()->toDateString();
            $imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
            $image_resize = Image::make($image->getRealPath());   
            $image_resize->resize(1600,1066);
            if (!file_exists('storage/uploads/post'))
            {
                mkdir('storage/uploads/post',0777,true);
            }
            //$image->move('storage/uploads/post',$imagename);
            $image_resize->save('storage/uploads/post/'.$imagename);
        }else{
            $imagename = "default.png";
        }

         $post = new Post();
        $post->user_id = Auth::id();
        $post->title = $request->title;
        $post->slug = str_slug($request->title);
        $post->image = $imagename;
        $post->save();
        Toastr::success('Post Successfully Save:)','Success');
        return redirect()->route('admin.post.index');

    }

// view page return 
 public function index()
    {
        $posts = Post::latest()->get();
        return view('admin.post.index',compact('posts'));
    }

// View

@foreach($posts as $post)
  <img src="{{asset('storage/uploads/post/'.$post->image)}}" alt="{{$post->title}}" />
@endforeach

推荐阅读