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')}}');

            }
        });
    }
Priya Negi
  • 117
  • 3
  • 15
  • Are you getting only last selected image? – G J Nov 27 '18 at 07:44
  • i want to upload all images – Priya Negi Nov 27 '18 at 07: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 ? – G J Nov 27 '18 at 07:45
  • try `image_upload.append('files', images.files[i]);` just get rid of `[]` array – G J Nov 27 '18 at 07: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. – Priya Negi Nov 27 '18 at 07:51
  • check this thread out https://stackoverflow.com/questions/12989442/uploading-multiple-files-using-formdata – G J Nov 27 '18 at 07:52
  • Not sure of server side though, but you may debug from browser console if files being posted by jQuery – G J Nov 27 '18 at 07:53
  • i am getting all images with in array while debugging using dd($request->all()); but unabling to upload all images . – Priya Negi Nov 27 '18 at 07:56

1 Answers1

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')}}');

            }
        });
    }
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57