使用ajax和laravel上载多个文件无效

问题描述 投票:0回答:1

我的代码有问题。问题是,当我使用Jquery Ajax(Front)和Laravel(Back)上传多个文件时,它仅上传了一个文件,而不是所有文件。

index.blade.php(窗体)

                <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文件逻辑@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());

谢谢。

php jquery ajax laravel form-data
1个回答
0
投票

我认为问题在于,两种情况下您都使用time()生成随机文件名。由于每行可能需要不到一秒钟的时间,因此time()将为两者返回相同的值,这意味着文件#2与文件#1具有相同的名称并将覆盖它。

尝试使用不同的文件名生成方式,也许只是像file1file2这样的静态名称,而不是time(),或者使用this thread中提到的一种技术来生成随机文件名。

© www.soinside.com 2019 - 2024. All rights reserved.