Reputation: 13
I know this has been asked a lot....but none of the answers I am coming across are helping. This is something ive done many times before...but on this occasion, im hitting a problem.
Im am trying to upload a zip file, via ajax, without submitting the form, just the field. I append the file to the formdata object...but the formdata is always empty (checking it before i send via ajax). $_FILES array server side is also always empty.
Can anyone see whats wrong, ive tried many variations... If i console.log(jQuery("#file_import")[0].files[0]); I see the file data.
var fileInput = jQuery("#file_import")[0];
var formData = new FormData();
formData.append("zipfile",fileInput.files[0]);
jQuery.ajax("/whatever/url", {
method: "POST",
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false,
onSuccess: function(response){
alert("whatever...");
}
});
Thanks in advance. Shaun
Upvotes: 1
Views: 708
Reputation: 7464
When you say "the formdata is always empty," are you trying to check it using formdata.entries()
, or are you using formData.get('zipfile')
? I think only the second of these will work.
EDIT: here is my exact code, client and server side.
$(document).ready(function() {
$('#start').click(function() {
var fileInput = $("#file_import")[0];
var formData = new FormData();
formData.append("zipfile",fileInput.files[0]);
$.ajax("test.php",{
method: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response){
$('#output').html(response);
}
});
});
});
HTML:
<input type="file" id="file_import"/>
<button id="start">Start</button>
<div id="output">
</div>
PHP:
<?php
print_r($_FILES);
$t = $_FILES['zipfile'];
$date = new DateTime();
$d = $date->format('Y-m-d_H-i-s');
move_uploaded_file($t['tmp_name'], "asdf_$d.zip");
?>
Upvotes: 1