Upload file in laravel with ajax jquery

·

Laravel 7.2 routing with route group auth guard check with prefix

Hello to all, welcome to therichpost.com. In this post, I will tell you, How to Upload file in laravel with ajax jquery? Like I always say that laravel is the best Mvc php framework.

Laravel file upload with jquery ajax formdata.

Here is this post, we will upload file in laravel with ajax and here is working and tested code:
//View file code:
<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>

//jscode

$(document).ready(function(){ 
    $("input").change(function(){

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

 });
});

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

//Controller File Code:
 public function uploadSubmit(Request $request){

        $files = [];
       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) ;
                $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);        
    }

 if you have any query related this post then please do ask.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.