Call to a member function getClientOriginalName() on null laravel

纵饮孤独 提交于 2020-07-23 06:36:28

问题


I keep on getting this error when I try to upload a pdf document file, does anybody have any idea how to solve this?

I had tried looking for similar problems but still can't solve it(eg: Upload pdf file using Laravel 5)

I tried doing dd() to see if the file have been uploaded and it did show the file name but the error said Call to a member function getClientOriginalName() on null, so now I'm kind of confused on what to do now.

Here are my codes, thanks in advance for helping.

Controller:

 class CreateController extends Controller
{
    public function create(){

    return view('create');
}
public function store(Request $request){

  $uniqueFileName = uniqid() . $request->get('upload_file')->getClientOriginalName() . '.' . $request->get('upload_file')->getClientOriginalExtension();

   $request->get('upload_file')->move(public_path('files') . $uniqueFileName);
//dd($request);
   return redirect()->back()->with('success', 'File uploaded successfully.');
}

create.blade.php

   <form  enctype="multipart/form-data" class="form-horizontal" method="post" action="{{ url('/user')}}">

             {{  csrf_field()  }}
          <div class="form-group">
     <label for="upload_file" class="control-label col-sm-3">Upload File</label>
     <div class="col-sm-9">
          <input class="form-control" type="file" name="upload_file" id="upload_file">
     </div>
</div>


 <div class="form-group">
            <div class="col-md-6-offset-2">
              <input type="submit" class="btn btn-primary" value="Save">
            </div>
          </div>
</form>

Route:

Route::get('/user/create','CreateController@create');
Route::post('/user','CreateController@store');

回答1:


You need to use the file() function to have access to your uploaded file

$request->file('upload_file')




回答2:


Try to put the file into a var.

$file = $request->file('upload_file');

And get the extension and name from it.

 $uniqueFileName = uniqid() . $file->getClientOriginalName() . '.' . $file->getClientOriginalExtension();

Hope it helps.




回答3:


The key to solving this problem is that you must write getClientOriginalName() function in the if clause just like that:

if($request->hasFile('logoImage')){
    $logoImage = $request->file('logoImage');
    $name = $logoImage->getClientOriginalName();
}



回答4:


use this code in your tag form enctype="multipart/form-data"

<form method="" action="" enctype="multipart/form-data">


来源:https://stackoverflow.com/questions/46885325/call-to-a-member-function-getclientoriginalname-on-null-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!