简体   繁体   中英

File upload in laravel 4

I have coded this in controller and routes file in Laravel 4 and met with the errors like "Call to a member function move() on a non-object" and

     "Call to a member function getClientOriginalName() on a non-object"

Controller:

class AuthorsController extends BaseController{
    public $restful = true;


    public function post_files()
    {

         $input = Input::all();
        $rules = array(
             'file' => 'image|mime:jpg,gif,png|max:3000',
        );

         $validation = Validator::make($input, $rules);

         if ($validation->fails())
         {
           return Response::make($validation->errors->first(), 400);
         }


        $file = Input::file('file'); // your file upload input field in the form should be named 'file'

        $destinationPath = 'public/uploads/'.str_random(8);
        // $filename = $file->getClientOriginalName();
        $filename = $file['name'];
        //$extension =$file->getClientOriginalExtension(); //if you need extension of the file
        $uploadSuccess = Input::file('file')->move($destinationPath, $filename);



        if( $uploadSuccess ) {
           return Response::json('success', 200); // or do a redirect with some message that file was uploaded
        } else {
           return Response::json('error', 400);
        }
    }

}

Routes:

Route::post('post_files','AuthorsController@post_files');

What does your form look like?

In Laravel 4 if you are uploading a file you need to open the form for files

{{  Form::open(array('url' => 'my/path', 'files' => true)) }}

Once you open your form for files the method getClientOriginalName() will work.

also make sure that your input is for a file

{{ Form::file('file') }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM