0

i have some problem with my code. The problem is when i upload multiple file with Jquery Ajax(Front) and Laravel(Back) its only uploaded one file not all files.

index.blade.php (form)

                <input type="file" name="file[]" class="form-control-file file-1">
                <input type="file" name="file[]" class="form-control-file file-2">

index.blade.php (Ajax Jquery)

  var data = new FormData();

  data.append('file[0]', $('.file-1')[0].files[0]);
  data.append('file[1]', $('.file-2')[0].files[0]);

  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });

  $.ajax({
    url: '{{ url('/layanan/file/users/store') }}',
    type: 'POST',
    data: data,
    processData: false,
    contentType: false,
    success: function(response){
      mprogress.end();
      console.log(data);
    },
  });

php file logic @store

    $request->file[0]->move(public_path('file'), time().'.'.$request->file[0]->extension());
    $request->file[1]->move(public_path('file'), time().'.'.$request->file[1]->extension());

Thanks.

1 Answers1

1

I think the problem is that you use time() to generate random file name on both cases. Since each line is likely to take less than a second, time() will return the same value for both, meaning that file#2 will have the same name as file#1 and will override it.

Try using different file name generation, maybe just static names like file1 and file2 instead of time(), or generate random file names with one of the techniques mentioned in this thread.

Pavel Lint
  • 3,252
  • 1
  • 18
  • 18