我如何上传多个图像并在laravel 5.3中获取它?

时间:2017-07-03 21:32:32

标签: php laravel

我如何使用laravel 5.3上传多个图像并将其显示在视图中?

我的控制器功能是:

public function newOffer(Request $request){
    $validate_marge['img'] = 'required|image|mimes:png,jpg,jpeg';
    $validator = Validator::make($request->all(), $validate_marge);
    if ($validator->fails()){
        return back()->withInput()->withErrors($validator);
    }else{
        $post = new Post();
        if (Input::hasFile('img')){
            $file = Input::file('img');
            $file->move(public_path('img/offers').'/', $file->getClientOriginalName());
            $post->img = $file->getClientOriginalName();
        }
    }
    $post->title = Input::get('title');
    $post->category_id = Input::get('category_id');
    $post->second_title = Input::get('second_title');
    $post->description = Input::get('description');
    $post->location = Input::get('location');
    $post->price = Input::get('price');
    $post->save();
    return back();
}

并且HTML表单是:

<form class="form-horizontal" method="post" action="{{ url('newOffer') }}"
  enctype="multipart/form-data">
{{ csrf_field() }} <div class="form-group">
    <label class="col-md-4 control-label">Select IMG's</label>
    <div class="col-md-6">
        <input type="file" class="form-control" id="image"
               name="images[]"
               required
               data-validation-required-message="Please choose image" multiple>
        <p class="help-block">{{$errors->first('images')}}</p>
    </div>
</div> <input type="submit" value="Add" class="btn btn-primary" style="width: 100%"></form>

我在Controller中做了什么以及如何在帖子中预览? 谢谢大家

1 个答案:

答案 0 :(得分:1)

更改

 if (Input::hasFile('img')){
        $file = Input::file('img');
        $file->move(public_path('img/offers').'/', $file->getClientOriginalName());
        $post->img = $file->getClientOriginalName();
    }

        if (Input::hasFile('img')){
                $files = Input::file('img');
                foreach ($files as $file){
                $file->move(public_path('img/offers').'/', $file->getClientOriginalName());
                }
                    $post->img = $file->getClientOriginalName();
                    $post->title = Input::get('title');
                    $post->category_id = Input::get('category_id');
                    $post->second_title = Input::get('second_title');
                    $post->description = Input::get('description');
                    $post->location = Input::get('location');
                    $post->price = Input::get('price');
                    $post->save();

            }
 return back();

您只需循环浏览上传的文件