Javascript 使用fetch api发送带有图像的数据,但文件数组为空
我的意图是尝试使用FetchAPI将json传递给php,json pases中的所有数据(除了文件中的数据)以及我使用var dump检查接收到的数据,为什么我不能获取文件数据? 发布数据:我没有复制表单的所有输入Javascript 使用fetch api发送带有图像的数据,但文件数组为空,javascript,php,json,fetch,Javascript,Php,Json,Fetch,我的意图是尝试使用FetchAPI将json传递给php,json pases中的所有数据(除了文件中的数据)以及我使用var dump检查接收到的数据,为什么我不能获取文件数据? 发布数据:我没有复制表单的所有输入 <form method="post" id='almacenInfo' enctype="multipart/form-data" name='almacenInfo'>
<form method="post" id='almacenInfo' enctype="multipart/form-data" name='almacenInfo'>
<label for="NombreInput">Nombre de producto</label>
<input type="text" class="form-control" id="NombreInput" placeholder="Nombre">
<div id='content_files'>
<button type="button" class="subir_archivos fa fa-upload">
<input id="upload_input" type="file" name="archivos" filename="name" accepted=".png,.jpg,.jpeg,.svg">
</button>
</div>
<div class="modal-footer">
<button type='submit' class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</form>
在前端执行控制台数据日志时使用json:
后端$obj的var转储:
我认为您会得到null,因为当您使用php读取img值时,它是一个二进制文件 因此,请尝试使用FormData()创建正确的Json
var img = []
form.addEventListener('submit', function(e){
e.preventDefault();
let data = {
opcion: form.getAttribute('modalTipo'),
idProducto: form.getAttribute('idProducto'),
nombre: document.getElementById('NombreInput').value,
precio: document.getElementById('PrecioInput').value,
cantidad: document.getElementById('CantidadInput').value,
categoria: document.getElementById('EtiquetasInput').value,
descripcion: document.getElementById('descripcionInput').value,
img: img
};
console.log(data);
fetchData(data);
});
document.getElementById('upload_input').addEventListener('change', function(e){
if (this.files.length > 0) {
let fileName = this.files[0].name;
let exists = false;
img.forEach(i => {
if (i.name == fileName) {
exists = true;
}
});
console.log(exists);
if (exists) {
console.log('ya existe esta imagen');
} else{
document.getElementById('content_files').append(fileName) ;
img.push(this.files[0]);
}
}
})
<?php
include_once('./conexion.php');
include_once('./apis/apiAlmacen.php');
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
var_dump($obj);
?>