欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

laravel multiple file upload 上传多个图像 有大用

Laravel 5.3 multiple file uploads

Ask QuestionAsked Active 10 months agoViewed 68k times27

How can I upload multiple files in Laravel 5.3. If I try it with 1 image it works but multiple images are not uploaded.

This is my code:

if($request->hasFile('attachment')) {
    foreach($request->allFiles('attachments') as $file) {
        $file->store('users/' . $user->id . '/messages');
    }
}

Improve this questionedited Feb 7 '20 at 16:56Max Base5331 gold badge5 silver badges12 bronze badgesasked Oct 4 '16 at 7:05Jamie8,24020 gold badges68 silver badges155 bronze badges

Add a comment

7 Answers   

看下面的红色部分比较重要




ActiveOldestVotes60

It works now like this:

$files = $request->file('attachment');

if($request->hasFile('attachment'))
{
    foreach ($files as $file) {
        $file->store('users/' . $this->user->id . '/messages');
    }
}

I had to append [] after the value of the name attribute, so:

<input type="file" name="attachment[]" multiple>

Improve this answeredited Nov 2 '17 at 2:37joshuamabina1,21017 silver badges25 bronze badgesanswered Oct 4 '16 at 7:45Jamie8,24020 gold badges68 silver badges155 bronze badges

Add a comment8

This is Controller to upload multiple files in laravel:

    public function fileUpload(Request $request)
    {
        if ($request->hasfile('filenames')) {
            foreach ($request->file('filenames') as $file) {
                $name = $file->getClientOriginalName();
                $file->move(public_path() . '/mytestfile/', $name);
                $data[] = $name;
            }
            return back()->with('Success!','Data Added!');
        }
    }

This view file in resources:

<html lang="en">
<head>
    <title>Multiple Image Upload</title>
    <script src="jquery/1.9.1/jquery.js"></script>
    <link rel="stylesheet" href="3.3.6/css/bootstrap.min.css">
</head>
<body>

<div class="container lst">
    <h3 class="well">Test Muliple Image Upload</h3>

    <form method="post" action="{{url('image-upload')}}" enctype="multipart/form-data">
        {{csrf_field()}}

        <div class="input-group hdtuto control-group lst increment" >
            <input type="file" name="filenames[]" class="myfrm form-control" multiple>
            <div class="input-group-btn">
                <button class="btn btn-success" type="button"><i class="fldemo glyphicon glyphicon-plus"></i>Add</button>
            </div>
        </div>

        <button type="submit" class="btn btn-success" style="margin-top:10px">Submit</button>
    </form>
</div>



<script type="text/javascript">
    $(document).ready(function() {
        $(".btn-success").click(function(){
            var lsthmtl = $(".clone").html();
            $(".increment").after(lsthmtl);
        });
        $("body").on("click",".btn-danger",function(){$(this).parents(".hdtuto control-group lst").remove();
        });
    });
</script>

</body>
</html>

Improve this answeredited Jul 31 '20 at 8:14סטנלי גרונן2,74021 gold badges43 silver badges62 bronze badgesanswered Jul 31 '20 at 7:41umayanga isuru811 silver badge2 bronze badges

Add a comment2

Solved it with this one a simplier approach. Just make sure that your input file type is like this <input type="file" name="images[]" multiple>

$i = 0;
foreach($request->file('images') as $file){
    $photo = new Photo;
    // name it differently by time and count
    $imageName = time() . $i . '.' . $file->getClientOriginalExtension();
    // move the file to desired folder
    $file->move('folderName/', $imageName);
    // assign the location of folder to the model
    $photo->image = 'folderName/' . $imageName;
    $photo->status = 1;
    $photo->save();
    $i++;
}

Improve this answeredited Feb 7 '20 at 16:48chriscatfr2,4923 gold badges22 silver badges32 bronze badgesanswered Jul 5 '19 at 9:54Edeeson Opina212 bronze badgesAdd a comment1

Try some thing like this:

public function multiple_upload() {
    // getting all of the post data
    $files = Input::file('images');

    // Making counting of uploaded images
    $file_count = count($files);

    // start count how many uploaded
    $uploadcount = 0;

    foreach($files as $file) {
        $rules = array('file' => 'required');

        //'required|mimes:png,gif,jpeg,txt,pdf,doc'

        $validator = Validator::make(array('file'=> $file), $rules);

        if($validator->passes()){
             $destinationPath = 'uploads';
             $filename = $file->getClientOriginalName();
             $upload_success = $file->move($destinationPath, $filename);
             $uploadcount ++;
         }
    }
}

Improve this answeredited Dec 10 '18 at 7:00Tadas V.6171 gold badge9 silver badges18 bronze badgesanswered Oct 4 '16 at 7:10Mayank Pandeyz23.3k3 gold badges29 silver badges52 bronze badges

Add a comment1

Controller.Php / Laravel 5.7.28

$files = $request->file('product_image_id');
if($request->hasFile('product_image_id')){
    foreach ($files as $file) {
        $name = time(). $file->getClientOriginalName();
        $file->move('images',$name);
        $productImage = ProductImage::create(['image'=>$name]);
        $input ['product_image_id'] = $productImage->id;
    }
}

Improve this answeredited Feb 7 '20 at 11:45Max Base5331 gold badge5 silver badges12 bronze badgesanswered May 10 '19 at 19:58Rashinda Sandaru112 bronze badgesAdd a comment0

If you want to still working with blade you can use this:

{{ Form::open(array('url' => 'upload', 'files'=>true)); }}  (<或者 form class="form-horizontal"  enctype="multipart/form-data"  action=""  method="POST">)
{{ Form::file('gallery[]', array('multiple'=>true,'accept'=>'image/*'));  }}  (或者 <input type="file" class="form-control" name="photos[]" multiple />)
{{ Form::submit();  }}
{{ Form::close();  }}

And in your Controller :

files = $request->file('gallery');

if($request->hasFile('gallery'))
{
    foreach ($files as $file) {
       // $file->store('users/' . $this->user->id . '/messages');
        //dump($file);
    }
}

Improve this answeranswered Jan 22 '18 at 9:37Malki Mohamed1,0521 gold badge15 silver badges34 bronze badgesAdd a comment0

This is how my blade looks like:

<div class="form-group row">
                                <label for="gallery-image" class="col-sm-3 text-left control-label col-form-label">Photo</label>
                                <div class="col-md-9">
                                    {{-- <input type="file" name="images[]" multiple> --}}
                                    <input type="file" class="form-control form-control-file"
                                     id="gallery-image" value="{{ old('gallery-image') }}" required name="gallery-image[]" multiple/>
                                     <span class="below-image-upload-msg">Advised image dimensions: 1920 x 450 pixels. File size should be less than 2Mb per image.</span>
                                </div>
                                @error('image')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                                @enderror
                            </div>

And this is how the store function in the controller looks like:

public function store(Request $request){
    $validation = Validator::make($request->all(), array(
        'gallery-id'    => 'required|integer|min:0',
        'gallery-image' => 'required|image|nullable|mimes:jpeg,png,jpg,gif|max:2048',
    ));
    $fileNameToStore="no-image.jpg";

    if(request('gallery-image'))
    {
        $iCount=0;
        foreach($request->file('gallery-image') as $thisImage){
            $fileNameWithExtension = $thisImage->getClientOriginalName();
            $memberName = Auth::user()->MemberProfile->member_tourist_office_name;
            

            $extension=$thisImage->getClientOriginalExtension();
            
            $fileNameToStore = $fileName.'_'.time().$iCount.'.'.$extension;

            $path= $thisImage->storeAs('public/images/members/gallery-images',$fileNameToStore);


            $isEnabled                                   = "0";   
            $galleryImage                                = new GalleryImage();
            $galleryImage->gallery_id                    = request('gallery-id');
            $galleryImage->gallery_image_caption         = " "; 
            $galleryImage->gallery_image                 = $fileNameToStore;
            $galleryImage->isEnabled                     = $isEnabled;

            $galleryImage->save();
            $iCount++;
        }
        return redirect('/galleryimage/create')->with('success', 'Image(s) successfully added to gallery!');
    }
}

Improve this answeranswered Jul 4 '20 at 7:59hackernewbie6337 silver badges6 bronze badgesAdd a comment

Your Answer

来自 https://www.google.com.hk/search?q=laravel+multiple+file+upload&newwindow=1&safe=strict&source=hp&ei=zyu4YMamKdrJ0PEP84q_mAM&iflsig=AINFCbYAAAAAYLg53-URWqjC01QUDW2EnXVfd1KWC-3E&oq=laravel+multi&gs_lcp=Cgdnd3Mtd2l6EAMYADICCAAyAggAMgIIADICCAAyAggAMgIIADICCAAyAggAMgIIADICCABQvgpYzCZg_15oAHAAeACAAdMBiAGvFJIBBTAuNS44mAEAoAEBqgEHZ3dzLXdpeg&sclient=gws-wiz



普通分类: