在Laravel中上传文件时出错:在null上调用成员函数

时间:2017-08-07 08:39:47

标签: php html database laravel

我想在laravel中上传文件。

我在控制器中使用了这段代码:

function store1(Request $request){
    $file=$request->file('myfile');
    $folder=$request->file('folder');
    $link=$request->input('link');

    $filename1 = $file->getClientOriginalName();
    $filename2 = $folder->getClientOriginalName();

    //$projectname
    $path="files/";
   $file->move($path,$filename1);
   $folder->move($path,$filename2);

   DB::table('groups')->update(['last_report'=>$filename1,'DropBox'=>$filename2]);

    return view('successfulUpload');
}

我希望用户能够上传多个文件,但它会在null上显示对成员函数getClientOriginalName()的调用。

1 个答案:

答案 0 :(得分:0)

尝试在Laravel中进行多次上传。

HTML表单:

<form method="post" action="controller/function" enctype="multipart/form-data">
  <input type="file" name="files[]" multiple />
  <input type="submit" />
</form>

在您的控制器中:

        // get posted input file
        $files = Input::file('files');
        $errors = "";
        $file_data = array();

        foreach($files as $file) 
        {

            if(Input::hasFile('files'))
            {
              // validating each file.
              $rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
              $validator = Validator::make(

                    [
                        'file' => $file,
                        'extension'  => Str::lower($file->getClientOriginalExtension()),
                    ],
                    [
                        'file' => 'required|max:100000',
                        'extension'  => 'required|in:jpg,jpeg,bmp,png,doc,docx,zip,rar,pdf,rtf,xlsx,xls,txt'
                    ]
                );

              if($validator->passes())
              {

                // path is root/uploads
                $destinationPath = 'path/to/upload';
                $filename = $file->getClientOriginalName();

                $upload_success = $file->move($destinationPath, $filename);

                if($upload_success) 
                {

                   //do after success ....

                } 
                else 
                {
                   $errors .= json('error', 400);
                }


              } 
              else 
              {
                // redirect back with errors.
                return Redirect::back()->withErrors($validator);
              }
            }

        }