在Laravel中使用Ajax和JQuery上传多个图像

时间:2018-11-27 07:41:20

标签: jquery ajax laravel

我正在使用Ajax和Jquery上传多个图像。在请求中将图像从视图传递到控制器时,我正在以阵列形式获取所有图像,现在仅上传单个图像。要预览所有图像,仅预览单个图像。我要上传所有图像并预览所有图像。

路线:

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

控制器:

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

       }

      }

   }

查看:

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

            }
        });
    }

1 个答案:

答案 0 :(得分:1)

您的控制器看起来像这样

  

首先u上传所有图像,然后获取带有路径的图像文件名

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 

您的js代码看起来像这样

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

            }
        });
    }