Laravel将图像上传到数据库 [英] Laravel upload images to database

查看:48
本文介绍了Laravel将图像上传到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试上传图片:

查看(部分):

 <input type="file" name="image" />

Countoller:

Countoller:

   public function store(Request $request){
        dump($request->all());
        $this->validate($request,[
            'title'=>'required|max:255',
         //   'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'text'=>'required',
        ]);
        $imageName = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('images'), $imageName);
        dump($request);
        $data=$request->all();
      dump($data);
        $aticle=new Article;
        $aticle->fill($data);
    }

转储请求:

"title" => "fgdfd"
  "alias" => "dg"
  "desc" => "fdgfgd"
  "text" => "gd"
  "image" => "IMG_0002.JPG"
  "tag" => "hg"

如何在MySql数据库中放置图像?

How do I put an image in MySql database?

推荐答案

作为文档描述,则应该使用 $ request 上的 file()方法访问上载的文件,而不是文件字段的名称.

As the docs describe, you should be using the file() method on the $request to access the uploaded file, not the name of your file field.

在您的情况下,这意味着:

In your case, that means:

// Use the file() method to access the uploaded file
$imageName = time() . '.' . $request->file('image')->getClientOriginalExtension();

// storeAs() allows you to move a file while specifying a new filename.
// $path will be the fully qualified path to the file, including filename.
$path = $request->file('image')->storeAs(public_path('images'), $imageName);

从您的问题尚不清楚,您是否要将文件路径或实际的二进制文件内容保存为BLOB.这两种方法都是这样做的:

It isn't clear from your question whether you want to save the file path in the database, or the actual binary file contents, as a BLOB. Here's how to do both:

// Create new article
$aticle=new Article;
$aticle->fill($data);

// Either save the path to the uploaded image in the DB
$aticle->featured_image = $path;
$aticle->save();

// OR
// Save the file binary contents in the DB
$aticle->featured_image = file_get_contents($path);
$aticle->save();

这篇关于Laravel将图像上传到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆