How to multiply uploaded files with Ajax?

5

I'm trying to upload multiple files using ajax and I came across the following problem, at first when I uploaded with just one file it would return me in php the array $_FILES with the name of my file, so I could move to my temp folder.

This way:

move_uploaded_file($_FILES['file']['tmp_name'], '../temp/' . $_FILES['file']['name']);

After I have adapted my JavaScript to send more than one file the array $_FILES comes empty.

Example:

var importadoresUrl = 'importador/exemplo.php?&acao=upload';

$('#upload').click(function() {
  $('#file_upload').click();
});

$("#file_upload").on("change", function(event) {
  files = event.target.files;
  var str = '',
    file = [];
  var formData = new FormData();

  $.each(files, function(key, val) {
    str += val.name + '\n';
    file[key] = $("#file_upload").prop('files')[key];
  });

  formData.append('file', file);
  $('#anexo').val(str + '\n');

  $.ajax({
    url: importadoresUrl,
    cache: false,
    contentType: false,
    processData: false,
    data: formData,
    type: 'post',
    success: function(data) {
      console.log(data);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><linkhref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet">
<br>
<br>
<br>
<div class="container">
  <div class='row'>
    <div class='col-md-4'></div>
    <div class='col-md-4'></div>
    <div class='col-md-4'>
      <input type="file" name="file_upload" id="file_upload" class="hidden" accept=".csv" multiple>
      <button id="upload" class='btn btn-default pull-right'><span class="glyphicon glyphicon-folder-open" aria-hidden="true"></span> Selecionar Arquivo</button>
    </div>
  </div>
  <label>Arquivo Selecionado:</label>
  <textarea id="anexo" disabled class='form-control' rows='6'></textarea>
</div>

How to Post:

  

Content-Disposition: form-data; name="file" [object file], [object   File]

    
asked by anonymous 25.01.2016 / 18:39

1 answer

2

I was able to send multiple files through ajax!

What did I do?

Instead of sending multiple files through an array called files I created for each file a variable file0, file1 etc ...

Then I read the array $_FILES that arrived with all the indices!

JavaScript No Each add:

 formData.append('file' + key, $("#file_upload").prop('files')[key]);

Now scroll through the files by moving to the temporary folder like this:

foreach ($_FILES as $value):
   move_uploaded_file($value['tmp_name'], '../temp/' . $value['name']);
endforeach;
    
25.01.2016 / 19:29