0

I am uploading multiple image using Ajax and Jquery. While passing image from view to controller in request i am getting all images in form of array now only single image is uploading.And to preview all image only single image is previewing.I want to upload all image and to preview all images.

Route:

Route::match(['post','get'],'/webadmin/uploadbanner','Webadmin\Banners@upload_banner_image');

Controller:

public function upload_banner_image(Request $request){
      if ($request->isMethod('get'))
          return view('/webadmin/uploadbanner');
      else {
          $validator = Validator::make($request->all(),
              [
                  'file' => 'image',
              ],
              [
                  'file.image' => 'The file must be an image (jpeg, png, bmp, gif, or svg)'
              ]);
          if ($validator->fails())
              return array(
                  'fail' => true,
                  'errors' => $validator->errors()
              );
              $files = $request->file('files');
             $total = $request->TotalImages;
             foreach($files as $file) {
                  for ($i = 0; $i < $total; $i++) {
                    $dir = 'public/assets/uploads/Banners/';
                    $imagename = $file->getClientOriginalName();
                    $filename = uniqid() . '_' . time() . '.' . $imagename;
                    $file->move($dir, $filename);
                    return $filename;
                  }

       }

      }

   }

View :

<div class="form-group">
                                <label for="field-ta" class="col-sm-2 control-label"> Featured Image</label>
                                <div class="col-sm-4">
                        <div class="full editp">
                        <label for="name" ></label>
                        <div id="image">

                             <img width="100%" height="100%" id="preview_image" src="https://projects.caresortsolutions.com/Elearn/public/assets/Webadmin/images/attach-1.png"/>
                       <i id="loading" class="fa fa-spinner fa-spin fa-3x fa-fw" style="position: absolute;left: 40%;top: 40%;display: none"></i>
                        </div>
                        <p>
                            <div class="form-group">
                                <div class="col-sm-offset-1 col-sm-10">
                                    <div class="checkbox">
                                        <label>
                            <a href="javascript:upload_banner()" style="text-decoration: none;" class="btn btn-success">
                                <i class="glyphicon glyphicon-edit "></i> upload image
                            </a>&nbsp;&nbsp;
                            <a href="javascript:removeFile()" style="color: white;text-decoration: none;" class="btn btn-red">
                                <i class="glyphicon glyphicon-trash "></i>
                                Remove
                            </a>
                                </div>
                                </div>
                            </div>
                        </p>
                        <input type="file" id="file" style="display: none" multiple/>
                        <input type="hidden" name="file_name[]" id="file_name" />
                        </div> </div>
                            </div>

Ajax :

var j = jQuery.noConflict();
    function upload_banner(){
        j('#file').click();
    }
     j('#file').change(function () {
         if (j(this).val() != '') {
            upload(this);
      }
    });
    function upload(img) {
        let image_upload = new FormData();
        image_upload.append('_token', '{{csrf_token()}}');
        j('#loading').css('display', 'block');
        let TotalImages = j('#file')[0].files.length; 
         let images = j('#file')[0]; 
         for (let i = 0; i < TotalImages; i++) {
            image_upload.append('files[]', images.files[i]);
        }
        image_upload.append('TotalImages', TotalImages);
        j.ajax({
            url: "{{url('/webadmin/uploadbanner')}}",
            data: image_upload,
            type: 'POST',
            contentType: false,
            processData: false,
            success: function (data) {
                alert(data);
                if (data.fail) {
                  j('#preview_image').attr('src', '{{URL::to('/public/assets/Webadmin/images/attach-1.png')}}');
                    alert(data.errors['file']);
                }
                else {
                    j('#file_name').val(data);
                    j('#preview_image').attr('src', '{{URL::to('/public/assets/uploads/Banners/')}}/' + data);
                }
                j('#loading').css('display', 'none');
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
                j('#preview_image').attr('src', '{{URL::to('/public/assets/Webadmin/images/attach-1.png')}}');

            }
        });
    }
8
  • Are you getting only last selected image? Commented Nov 27, 2018 at 7:44
  • i want to upload all images Commented Nov 27, 2018 at 7:44
  • image_upload.append('files[]', images.files[i]); is replacing the previous files and retain the last one and you must be getting only last. Is that correct ? Commented Nov 27, 2018 at 7:45
  • try image_upload.append('files', images.files[i]); just get rid of [] array Commented Nov 27, 2018 at 7:47
  • i have tried this but its not working for me it avoids uploading image and return url with no image with in image tag. Commented Nov 27, 2018 at 7:51

1 Answer 1

1

your controller look like that

first u upload all the images and then get image file name with path

public function upload_banner_image(Request $request){
      if ($request->isMethod('get'))
          return view('/webadmin/uploadbanner');
      else {
          $validator = Validator::make($request->all(),
              [
                  'file' => 'image',
              ],
              [
                  'file.image' => 'The file must be an image (jpeg, png, bmp, gif, or svg)'
              ]);
          if ($validator->fails())
              return array(
                  'fail' => true,
                  'errors' => $validator->errors()
              );
             $files = [];  //store filename in this array.
            // $total = $request->TotalImages;  no need to check total images.
           if($request->files) {
             foreach($request->file('files') as $file) {
                    $dir = 'public/assets/uploads/Banners/';
                    $imagename = $file->getClientOriginalName();
                    $filename = uniqid() . '_' . time() . '.' . $imagename;
                    $file->move($dir, $filename);
                    $files[] = $dir.$filename;
            } //foreach
         } //if
                 //return all the filename with path ...
           return response()->json(['files' => $files]);
     } //else
 } //function 

your js code look like that

var j = jQuery.noConflict();
    function upload_banner(){
        j('#file').click();
    }
     j('#file').change(function () {
         if (j(this).val() != '') {
            upload(this);
      }
    });
    function upload(img) {
        let image_upload = new FormData();
        image_upload.append('_token', '{{csrf_token()}}');
        j('#loading').css('display', 'block');
        let TotalImages = j('#file')[0].files.length; 
         let images = j('#file')[0]; 
         for (let i = 0; i < TotalImages; i++) {
            image_upload.append('files[]', images.files[i]);
        }
        image_upload.append('TotalImages', TotalImages);
        j.ajax({
            url: "{{url('/webadmin/uploadbanner')}}",
            data: image_upload,
            type: 'POST',
            contentType: false,
            processData: false,
            success: function (data) {
                alert(data);
                if (data.fail) {
                  j('#preview_image').attr('src', '{{URL::to('/public/assets/Webadmin/images/attach-1.png')}}');
                    alert(data.errors['file']);
                }
                else {
                    if(data.files) {
                      data.files.forEach(function(item,key) {
                       //j('#file_name').val(item); //file with path
                          j('#preview_image').attr('src',item); //file with path
                       });    
                    } //if files get
                } //else
                j('#loading').css('display', 'none');
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
                j('#preview_image').attr('src', '{{URL::to('/public/assets/Webadmin/images/attach-1.png')}}');

            }
        });
    }
Sign up to request clarification or add additional context in comments.

5 Comments

its giving call to undefined member function getClientOriginalName on array() and iam using image_upload.append('files[]', images.files[i]); in ajax call
uploading works with changing foreach($request->file('files') as $file) {}
preview not getting all images but upload working proper.
@PriyaNegi u need to create <ul> html element add one by one image using <li>
@PriyaNegi great

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.