2017-12-23 7 views
0

に画像をアップロードする:Laravelは私がアップロードのイメージをしようとしているデータベース

ビュー(一部):

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

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データベースに画像を保存するにはどうすればいいですか?

答えて

0

理想的には、ファイルを場所に保存し、そのファイルへのパスをデータベースに保存します。

あなたはどのバージョンのLaravelを使用していますか?あなたが5.3以上にしている場合は次のことができます。

$path = $request->image->store('path/to/save/the/file'); 

これは、ランダムな名前のファイルが保存されます、そしてちょうどデータベースにそのパスを格納します。

たりすることができます:あなたが保存したファイル名を指定したい場合は

$path = $request->image->storeAs('path/to/save/the/file', 'filename.jpg'); 

0

As the docs describe$requestでは、ファイルフィールドの名前ではなく、アップロードされたファイルにアクセスするにはfile()メソッドを使用する必要があります。あなたのケースでは

、それは意味:

// 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として、データベース内のファイル・パス、または実際のバイナリファイルの内容を保存するかどうか、あなたの質問から明らかではありません。両方を行う方法は次のとおりです。

// 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(); 
関連する問題