Laravel 5.1: How to upload multiple files from three different file input fields?

霸气de小男生 提交于 2019-12-20 02:52:41

问题


I have a form in which user should at least select one file to be uploaded. I have three file input fields like this:

            <div class="form-group col-lg-4">
                {!! Form::label('file1', 'Select file 1', ['class' => 'control-label']) !!}
                {!! Form::file('files[]', ['id'=>'file1']) !!}
            </div>
            <div class="form-group col-lg-4">
                {!! Form::label('file2', 'Select file 2', ['class' => 'control-label']) !!}
                {!! Form::file('files[]', ['id'=>'file2']) !!}
            </div>
            <div class="form-group col-lg-4">
                {!! Form::label('file3', 'Select file 3', ['class' => 'control-label']) !!}
                {!! Form::file('files[]', ['id'=>'file3']) !!}
            </div>

I should validate the presence of at least one file and the mime types in a form request. Then in the store method of the related form controller, the original file names should be stored in the three corresponding database fields(namely file1, file2, file3).

How can I implement this?


回答1:


After some searching around I finally came up with a solution. First of all I modified the view to look like this:

<div class="form-group col-lg-4">
            {!! Form::label('file1', 'Select file 1', ['class' => 'control-label']) !!}
            {!! Form::file('file1', ['id'=>'file1']) !!}
        </div>
        <div class="form-group col-lg-4">
            {!! Form::label('file2', 'Select file 2', ['class' => 'control-label']) !!}
            {!! Form::file('file2', ['id'=>'file2']) !!}
        </div>
        <div class="form-group col-lg-4">
            {!! Form::label('file3', 'Select file 3', ['class' => 'control-label']) !!}
            {!! Form::file('file3', ['id'=>'file3']) !!}
        </div>

Then in the controller I used your suggested code:

$files =[];
        if ($request->file('file1')) $files[] = $request->file('file1');
        if ($request->file('file2')) $files[] = $request->file('file2');
        if ($request->file('file3')) $files[] = $request->file('file3');
        foreach ($files as $file)
        {
            if(!empty($file)){
                $filename=$file->getClientOriginalName();
                $file->move(
                    base_path().'/public/uploads/', $filename
                );
            }

        }


来源:https://stackoverflow.com/questions/31936336/laravel-5-1-how-to-upload-multiple-files-from-three-different-file-input-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!