[英]Upload image with Ajax and PHP
我想將圖像上傳到服務器,並控制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 */
}
});
});
$(".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 */
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.