I'm trying to receive an input file from HTML input through ajax with PHP... Here is the HTML:
<form id="file-form-real" method="POST" enctype="multipart/form-data"><input type="file" class="inputfile" id="carga-excelreal" name="carga-excelreal" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"><label for="carga-excelreal"><img src="img/MSExcel_2013_logo.svg"><span>Carga Archivo Costo Real</span></label><button type="submit" class="u-button" id="ubutton-real" onclick="uploadManager.sendReal();">Actualizar BD</button></form>
Here is the Javascript file uploadManager.js:
var uploadManager = {
sendReal: function(){
var form = document.getElementById("carga-excelreal");
var nameOr = form.value;
var splited = nameOr.split("\\");
var largo = splited.length;
var name = splited[largo-1];
var file = form.files;
var formData = new FormData();
formData.append('file', file);
formData.append('name', name);
var ajaxRequest= $.ajax({
url:"controllers/admin/UploadCostoReal.php",
data: formData,
type:"POST",
contentType:false,
processData:false,
cache:false,
success:function(response){
console.log(response);
}
});
}
}
Here is the PHP:
<?php
$name = $_POST['name'];
$file = $_FILES['file'];
if(move_uploaded_file($file,"../../docs/costo_real/".$name)){
$msg = "Uploaded Ok";
echo json_encode($msg, JSON_UNESCAPED_UNICODE);
}else{
$msg = "There was an error";
echo json_encode($msg, JSON_UNESCAPED_UNICODE);
}
?>
When print with print_r($_POST) and print_r($_FILES) here is the output:
Array
(
)
Array
(
[file] => [object FileList]
[name] => 1557 - Planilla Gestion de Compras 16.ago.2016.xls
)
I have the following questions:
-How can I read [object FileList], get the file and save it to a specific folder.
-(I've already saw that [file] is empty, .... why??, it is suposed to have the file).
-The general procedure is ok or I have to do with an action attribute in my form tag???
Also it might very helpful if someone knows how to put a loading gif (this last thing is not important as the main thing I've asked)
Thank you for the answers.