【问题标题】:File upload in laravel 4在 laravel 4 中上传文件
【发布时间】:2013-08-11 00:56:45
【问题描述】:

我已经在 Laravel 4 中的控制器和路由文件中对此进行了编码,并遇到了诸如“在非对象上调用成员函数 move()”和

之类的错误
     "Call to a member function getClientOriginalName() on a non-object"

控制器:

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);
        }
    }

}

路线:

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

【问题讨论】:

  • 显示包含表单的视图文件
  • 我正在从 postman rest api tester 传递一个文件
  • 文件发送了吗?在您的控制器操作中尝试 var_dump($_FILES)

标签: php image file upload laravel


【解决方案1】:

你的表单是什么样子的?

在 Laravel 4 中,如果您要上传文件,则需要打开文件表单

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

打开文件的表单后,getClientOriginalName() 方法将起作用。

还要确保您的输入是针对文件的

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

【讨论】:

  • 抱歉 OP 没有选择您的答案。感谢您的回答,为我节省了很多时间!
  • 第一次尝试时,我花了一段时间才弄明白。很高兴我能阻止其他人遇到同样的麻烦。
猜你喜欢
  • 2013-07-22
  • 2013-04-06
  • 2015-03-21
  • 2013-08-14
  • 2014-03-07
  • 2013-08-13
  • 2014-02-21
  • 2015-04-24
  • 1970-01-01
相关资源
最近更新 更多