Laravel 4 中的文件上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18140823/
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
File upload in laravel 4
提问by richa
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
我已经在 Laravel 4 的控制器和路由文件中对此进行了编码,并遇到了诸如“在非对象上调用成员函数 move()”之类的错误和
"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');
Route::post('post_files','AuthorsController@post_files');
回答by codivist
What does your form look like?
你的表格是什么样的?
In Laravel 4 if you are uploading a file you need to open the form for files
在 Laravel 4 中,如果您要上传文件,则需要打开文件表单
{{ Form::open(array('url' => 'my/path', 'files' => true)) }}
Once you open your form for files the method getClientOriginalName() will work.
打开文件表单后,方法 getClientOriginalName() 将起作用。
also make sure that your input is for a file
还要确保您的输入是针对文件的
{{ Form::file('file') }}