Laravel 5.8。如何上传文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55208700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:18:07  来源:igfitidea点击:

Laravel 5.8. How to upload file?

htmllaravel

提问by Loctarogar

I have simple Form:

我有简单的表格:

<form method="post" action="{{ route('company.store') }}">
    Logo: <br>
    <input name="logo" type="file"><br>

In my controller i try to save image with

在我的控制器中,我尝试用

$file = $request->file('logo')->store('avatars');

but i have error

但我有错误

 "Call to a member function store() on null"

dd($request->file('logo');shows 'null'

dd($request->file('logo');显示 'null'

How to reach file to save it?

如何到达文件以保存它?

回答by Rwd

To upload a file you need to add enctype="multipart/form-data"to you opening form tag:

要上传文件,您需要添加enctype="multipart/form-data"到您的打开表单标签中:

<form method="post" action="{{ route('company.store') }}" enctype="multipart/form-data">

If you don't include it then only the file name will be submitted and will cause

如果您不包含它,则只会提交文件名,并且会导致

$request->file('logo')

$request->file('logo')

to return nullbecause it isn't a file it's a string.

返回,null因为它不是一个文件,它是一个字符串。

回答by Danial Abbas

uploading file need a enctype="multipart/form-data"

上传文件需要一个 enctype="multipart/form-data"

      <form action="{{ route('company.store') }}" method="post" enctype="multipart/form-data"
             class="form-material">
               {{csrf_field()}}
          <div class="form-body">         
                 <h3 class="card-title">upload image</h3>
             <div class="form-group">
                <label class="control-label">image 1</label>
                <input type="file" name="image_path" class="form-control">
             </div>
          </div>
    </form>



Your Controller should look like this .


public function store(Request $request)
    {
        $this->validate($request,['image_path'=> 'required|image']);

        $company = new Company();
        if($request->hasFile('image_path'))
        {
      $company->image_path= $request->file('image_path')->store('company','public');
        }
        
        $company->save();

          return back()->with('success', 'Done!');

    }