【问题标题】:Unable to upload an image in Laravel 5.4无法在 Laravel 5.4 中上传图片
【发布时间】:2017-08-01 20:25:04
【问题描述】:

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

图片必须是图片。

如果我删除图像的验证,我会得到一个FatalErrorException

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

Intervention/Image 库提供的辅助函数。这可能意味着图片根本没有上传。

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>

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

我错过了什么?

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.4 intervention


    【解决方案1】:

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

    enctype="multipart/form-data"
    

    到您的表单中,而不是:

    <form action="/hq/foods" method="POST">
    

    你应该使用

    <form action="/hq/foods" method="POST" enctype="multipart/form-data">
    

    【讨论】:

    • 什么失误。非常感谢。
    【解决方案2】:

    如果你使用 Laravelcollective

                              {!! Form::open(['method'=>'post','files' => true,'url'=>'/hq/foods']) !!}
    

    或 使用 HTML

    <form action="/hq/foods" method="POST" enctype="multipart/form-data">
    

    【讨论】:

      【解决方案3】:

      你需要在你的 from 中添加 enctype="multipart/form-data"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-02
        • 2017-10-28
        • 2020-03-21
        • 1970-01-01
        • 2020-10-03
        • 2018-04-17
        • 1970-01-01
        • 2017-09-20
        相关资源
        最近更新 更多