您好,我需要知道如何使用 ajax 将图像插入到我的数据库中。
前段时间我学会了用 php 插入图像。但现在我需要通过 AJAX 来完成,这给我带来了问题。
假设这是我的表格:
Ingresar nombre producto
<input type="text" id="id_descripcion"><br>
<input type="file" id="id_file_imagen"><br>
<button class="btn-registrar-producto"> Registrar</button>
这是jQuery代码:
$(document).ready(function(){
$(".btn-registrar-producto").click(function(){
var nombre = $("#id_descripcion").val();
var file_imagen = $("#id_file_imagen").val();
$.ajax({
url:"php/registrar_producto.php",
method:"POST",
data:
{
nombre:nombre,
file_imagen:file_imagen,
},
dataType:"text",
success:function(data)
{
if(data=="OK"){
alert('Datos Registrados');
}else{
alert(data);
}
}
});
});
});
这是我的 PHP 代码:
<?php
include 'conexion.php';
$nombre=$_REQUEST['nombre'];
$imagen=$_FILES['file_imagen']['name'];
$ruta=$_FILES['file_imagen']['tmp_name'];
$destino='productos/'.$imagen;
copy($ruta, $destino);
$sql = "INSERT INTO tbl_producto (prod_nom, prod_imagen)
VALUES ('$nombre', '$destino')";
if ($conn->query($sql) === TRUE) {
$mensaje = "OK";
} else {
echo "Ups! Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
但它向我报告图像变量为空且未定义的错误。以前,我所做的是将它放在一个表单和 enctype="multipart/form-data" 属性中,但是自从我开始学习 ajax 后,我认为表单不再是必需的。
那么,有什么办法可以解决呢?提前致谢。
我已经修改了你代码中的小值,我在 中添加了属性
name
,input
以识别它们在 中的值PHP
,以便更新Base de datos
.我在表单中添加了两个属性,
id
并且enctype
.有了
id
它,我将通过Ajax
.enctype="multipart/form-data"
,当使用具有文件上传控件的表单时,此值是必需的。我们还必须考虑到,如果我们不在文档中添加
librería
of ,在标签内,示例将不起作用,有时会忘记一些小细节。jQuery
HTML
<head></head>
HTML
阿贾克斯
PHP (register_product.php)
您可以使用表单数据
https://developer.mozilla.org/en/docs/Web/Guide/Using_FormData_Objects