我想将图像上传到我的服务器,并在我的HTML代码中控制PHP回声。为此,我想使用jQuery Ajax,但我不知道如何使用Ajax将图像发送到PHP。这是一个大学项目,所以我不能使用任何类型的插件。
我的实际代码:
HTML
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
Prueba.php
define('MB', 1048576);
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 1*MB)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("../public/images/productos/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../public/images/productos/" . $_FILES["file"]["name"]);
echo "Stored in: " . "../public/images/productos/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
我想用这样的......
JS
$(".form").submit(function(){
$.ajax({
url: 'core/ctrlAdmin.php?prodInBD',
type: 'POST',
async: false,
data: ????
success: function(respuesta){
/* RECIVE HERE THE PHP ECHO */
}
});
});
答案 0 :(得分:1)
$(".form").submit(function(){
$.ajax({
url: 'core/ctrlAdmin.php?prodInBD',
type: 'POST',
async: false,
data: new FormData(this);
success: function(respuesta){
/* RECIVE HERE THE PHP ECHO */
}
});
});