3

I have tried majority of other questions here and other solutions and nothing has worked so far.

What I am trying to accomplish is upload images before Laravel's validation takes place, obviously I can't use the create function because it wont be hit until validation succeeds so I have made a custom function to do the file saving server side and trying to use Ajax to call that function every time a file is selected.

Current issue: doesn't seem like my Ajax is running on debugging its being skipped over,

second issue: I have a csrf token in my master template do i still need to add the ajax setup? if so is the way i am doing it correct.

Route:

Route::post('/upload', 'UploadController@uploadSubmit');

View:

<div>
    <input type="file" id="fileupload" name="photos[]" data-url="/upload" multiple />
    <br />
    <div id="files_list"></div>
    <p id="loading"></p>
    <input type="hidden" name="file_ids" id="file_ids" value="" />                    
 </div>

Ajax call:

  $(document).ready(function(){ 
    $("input").change(function(){
         alert('triggered');

         debugger;
         $('#fileupload').fileupload({

           $.ajaxSetup({
              headers: {
              'X-CSRF-TOKEN': $(meta[name="csrf-token"]).attr('content')
              }
              dataType: 'json',
              add: function (e, data) {
                  $('#loading').text('Uploading...');
                  data.submit();
              },
              done: function (e, data) {
                  $.each(data.result.files, function (index, file) {
                      $('<p/>').html(file.name + ' (' + file.size + ' KB)').appendTo($('#files_list'));
                      if ($('#file_ids').val() != '') {
                          $('#file_ids').val($('#file_ids').val() + ',');
                      }
                      $('#file_ids').val($('#file_ids').val() + file.fileID);
                  });
                  $('#loading').text('');
              }
            });
         });
      });
   });

Controller:

 public function uploadSubmit(Request $request){

        $files = [];
        dd(request());
       foreach($learnerFiles as $key => $learnerFile){   
           if(count($learnerFile) > 0){

                $path = $learnerFile->storeAs('public/uploads/learners', request('idNumber').'_'.$key.'.'.$learnerFile->extension());
                $search = 'public/' ;
                $trimmed = str_replace($search, '', $path) ;
                //dd($learnerFiles);
                $file = FileUpload::create([

                    'user_id'     => $learner->id,
                    'file_name'   => $key,
                    'path'        => $trimmed
                ]);
            }
            else{

            }

        $file_object = new \stdClass();
        $file_object->name = $key;
        $file_object->size = round(Storage::size($path) / 1024, 2);
        $file_object->fileID = $learner->id;
        $files[] = $file_object;
        }

        return response()->json(array('files' => $photos), 200);        
    }

1 Answer 1

2

I'm using the following method to upload images using Ajax call and Laravel back-end.

    var uploader = $('#image-uploader[type="file"]');
    var data = new FormData();
    $.each(uploader.files, function() {
        data.append('image[]', this);
    });
    data.append('_token', $('[name="csrf-token"]').attr('content'));
    var url = '/upload'; //Or any target path with post method
    $.ajax({
        url: url,
        method: 'POST',
        data: data,
        processData: false,
        contentType: false,
        success: function(data) {
            alert('succeed');
        }
    });

Consider you can access to image files in server-side using $_POST['image] array.
Hope this helps you.

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

2 Comments

It's non-English website. hikhodro.ir/car/register , you have to register before using this page.
Thank you I have finally gotten to my controller using your solution! up voted =)

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.