5
I am trying to upload multiple files using ajax and came across the following problem,
the beginning when I uploaded only one file it returned me in php the array $_FILES
with the name of my file, like this
I could move to my temp folder.
In this way:
move_uploaded_file($_FILES['file']['tmp_name'], '../temp/' . $_FILES['file']['name']);
After I adapted my Javascript to send more than one file the array $_FILES
come 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>
<link href="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 it looks in Post:
Content-Disposition: form-data; name="file" [Object File],[Object File]
Related or possible duplicate: http://answall.com/questions/106094/upload-ajax-selectr-multiplos-archives?rq=1
– Leonardo
@Ivcs Sergio’s answer is really excellent, but are examples of firing 1 ajax for each file, I was thinking of a solution to send them at once.
– Gabriel Rodrigues