4

First I want Apology for my eng.

Second I don't want to use any plugin.

I Want to upload Multiple image and I can do it without ajax, But I want to upload with Ajax. I Put my Code here.

<form action="{{route('image-upload.store')}}" method="post" enctype="multipart/form-data">
   {{csrf_field()}}
   <input type="file" id="image-upload" name="image_upload[]" enctype="multipart/form-data" multiple>  

  <button type="submit">save</button>
</form>                          

Controller :

if ($request->hasFile('image_upload')) {
        $images = $request->file('image_upload');
        foreach ($images as $image) {
            $randonName = rand(1, 200);
            $name = $image->getClientOriginalName();
            $storename = $randonName . '_' . $name;
            $image->move(public_path('images/test'), $storename);
        }
    }

return redirect()->back();

Above Code simply upload multiple image without Ajax.

Here Ajax :

html :

 <input type="file" id="image-upload" name="image_upload[]" enctype="multipart/form-data" multiple>

Ajax :

 $.ajaxSetup({
     headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
 });

$('#image-upload').change(function () {
    event.preventDefault();
    let image_upload = new FormData();
    let TotalImages = $('#image-upload')[0].files.length;  //Total Images
    let images = $('#image-upload')[0];  

    for (let i = 0; i < TotalImages; i++) {
        image_upload.append('images', images.files[i]);
    }
    image_upload.append('TotalImages', TotalImages);

    $.ajax({
        method: 'POST',
        url: '/image-upload',
        data: image_upload,
        contentType: false,
        processData: false,
        success: function (images) {
            console.log(`ok ${images}`)
        },
        error: function () {
          console.log(`Failed`)
        }
    })

})

Controller :

  if ($request->images) {
        $images = $request->images;
        $total=$request->TotalImages;
        $imagesName = $images->getClientOriginalName();
       $randonName = rand(1, 200);
        $images->move(public_path('/images/test'), $randonName . '.jpg');
        return response()->json($randonName);
    }

Now This Code Work Fine but only for one image. I know that I Sould put it Loop and I did But didn't get my Response.

So if anyone can tell me how do it?

Here My Efforts :

 if ($request->images) {
       $total=$request->TotalImages;
        $images = $request->images;
        for($j=0; $j<$total;$j++){
            $imagesName = $images->getClientOriginalName();
            $randonName = rand(1, 200);
            $images->move(public_path('/images/test'), $randonName . '.jpg');
        }
        return response()->json($randonName);
    }

  if ($request->images) {
        $images = $request->images;
        foreach ($images as $image) {
            $imagesName = $images->getClientOriginalName();
            $randonName = rand(1, 200);
            $image->move(public_path('/images/test'),$randonName . $imagesName . $randonName . '.jpg');
        }
    }
6
  • 1
    For this $request->images variable what you get output ? Commented Jul 21, 2018 at 11:48
  • return response()->json($request->images); .Output is an object ( [object Object] ) Commented Jul 21, 2018 at 12:01
  • 1
    can you please post response in your question? Commented Jul 21, 2018 at 12:57
  • thanks but i found problem. just need replace this simple ajax code : image_upload.append('images[]', images.files[i]); Commented Jul 21, 2018 at 13:04
  • Then post an answer that will help others or delete this question Commented Jul 21, 2018 at 14:29

2 Answers 2

3

this gonna work too this will send array of images so as to get it easily in controller

        for (let i = 0; i < TotalImages; i++) {
            image_upload.append('images[]', images.files[i]);
        }
Sign up to request clarification or add additional context in comments.

Comments

2

update your code as follows:

for (let i = 0; i < TotalImages; i++) {
    image_upload.append('images', images.files[i]);
}

to

for (let i = 0; i < TotalImages; i++) {
    image_upload.append('images' + i, images.files[i]);
}

this should help you to submit multiple images.

1 Comment

If you put +i in the iteration...formdata will add the number of iterations in front of the name file....so images0...images1 etc...how will you read this on server side?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.