如何在Laravel中上传文件?

时间:2019-11-18 18:08:05

标签: html laravel laravel-blade

这是将图像上传到数据库的代码。

b_hh

刀片

public function create(Request $request)

{
    $this->validate($request, [

        'comment' => 'required',
    ]);

    $mess = new messageUser;
    $mess->user_id = Auth::guard('userLogin')->user()->id;
    $mess->message = $request->comment;

    if($request->hasFile('image')){
        $filenameWithExtention = $request->file('image')->getClientOriginalName();
        $fileName = pathinfo($filenameWithExtention,PATHINFO_FILENAME);
        $extension = $request->file('image')->getClientOriginalExtension();
        $fileNameStore = $fileName .'_'.time().'.'.$extension;
        $path = $request->image->storeAs('images', $fileNameStore);
        $mess->attach = $fileNameStore;
    }

    $mess->save();
    return $mess;
}

代码成功发送了邮件,但没有上传图片。

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

if($request->hasFile('image')){
  $filenameWithExtention = $request->file('image')->getClientOriginalName();
  $fileName = pathinfo($filenameWithExtention,PATHINFO_FILENAME);
  $extension = $request->file('image')->getClientOriginalExtension();
  $fileNameStore = $fileName .'_'.time().'.'.$extension;
  $path = $request->photo->storeAs('images', $fileNameStore);
  $mess->attach = $fileNameStore;
}

更多访问this

谢谢。

注意:不要忘记运行php artisan storage:link

答案 1 :(得分:0)

请问是什么错误告诉我们,这会更好地指导您...顺便说一句,您可能会使用以下代码来修饰图像/文件

    if ($request->image) {
               $file = $request->File('image');
               $ext  = $student->username . "." . $file- 
   >clientExtension();
              $file->storeAs('images/', $ext);
              $student->image = $ext;
          }