无法在Laravel 5.4中上传图像

ano*_*nym 0 php laravel laravel-5 intervention laravel-5.4

我正在使用Laravel 5.4设置一个表单,用户可以在其中输入食物名称及其图像。尝试上传PNG或JPG图片时,出现以下内容Validation Error:

该图像必须是图像。

如果删除图像验证,则会得到FatalErrorException:

在null上调用成员函数getClientOriginalExtension()

这是Intervention /图片库提供的帮助程序功能。这可能意味着该图像根本没有上传。

FORM

<form action="/hq/foods" method="POST">
    {{ csrf_field()  }}

    <input type="text" name="name">
    <input type="file" name="image">
    <button type="submit" class="btn btn-success ">
        ADD FOOD ITEM
    </button>
</form>
Run Code Online (Sandbox Code Playgroud)

CONTROLLER

public function store(Request $request) {

    $this->validate($request, [
        'name'              => 'required|min:2|max:255',
        'image'             => 'required|image'
    ]);

    $food_category = FoodCategory::find($request->food_category_id);
    $food = new Food;
    $food->name = $request->name;

    $image = $request->file('image');
    $filename = time() . '.' . $image->getClientOriginalExtension();
    $location = public_path('img/foods/' . $filename);
    Image::make($image)->resize(800, 400)->save($location);
    $food->image = $filename;

    $food->save();

    Session::flash('success',
        '
        <h4>Success!</h4>
        <p>The food item has been added to the Menu.</p>
    ');
    return back();
}
Run Code Online (Sandbox Code Playgroud)

我想念什么?

Mar*_*łek 6

要上传图片,您需要添加:

enctype="multipart/form-data"
Run Code Online (Sandbox Code Playgroud)

而不是:

<form action="/hq/foods" method="POST">
Run Code Online (Sandbox Code Playgroud)

你应该使用

<form action="/hq/foods" method="POST" enctype="multipart/form-data">
Run Code Online (Sandbox Code Playgroud)