Buenas estoy dandole vueltas a esto desde hace mas de 3 horas por eso solicito su ayuda. Necesito replicar el comportamiento de un formulario normal que carga una imagen y la envia a php para luego subirla a mi base de datos. Intente lo siguiente.
const file=document.getElementById("file");
const btn=document.getElementById("btn");
btn.addEventListener("click",presclick);
function presclick()
{
const archivos=file.files;
var formData=new FormData();
formData.append("img",archivos);
var xhr=new XMLHttpRequest;
xhr.open("POST","agregarimg.php");
xhr.send(formData);
xhr.onreadystatechange=function()
{
if(xhr.status==200&&xhr.readyState==4)
{
console.log(xhr.responseText);
}
}
}
<input id="file" type="file">
<button type="button" id="btn">Enviar</button>
<?php
header("Acces-Control-Allow-Origin:*");
$archivos;
if(isset($_FILES["img"]))
{
$archivos=$_FILES["img"];
$imgtemporal=$_FILES["img"]["tmp_name"];
$data=file_get_contents($imgtemporal);
$conexion=new PDO("mysql:host=localhost;dbname=prueba","usuario","contraseña");
$conexion->exec("SET CHARACTER SET UTF8");
$conexion->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$consulta="INSERT INTO imgprueba (img) values (:img)";
$respuesta=$conexion->prepare($consulta);
$respuesta->bindValue(":img",$data);
$respuesta->execute();
$mensaje="Se subio la imagen"
echo "se subio la imagen"
}
?>
Sin embargo al parecer en el archivo php no recibo la imagen para poder subirla a la base de datos. Intente cambiando el "$_FILES" por "$_POST", y si me recibe el archivo, pero me sale el siguiente error
[10-Jul-2020 22:10:54 UTC] PHP Warning: Illegal string offset 'tmp_name' in /home/hiddenso/public_html/....
Que estoy haciendo mal?