javascript - 使用 jquery 发送文件并在 PHP 中接收(无插件)
问题描述
我正在尝试使用带有表单的 AJAX 发送文件,但 PHP 文件似乎什么也没收到,不仅是文件,还有表单元素。在 PHP 中,如果我尝试从我得到一个值,$_POST
我得到一个Undefined Index
. 我试过了:
$("#animal-insert").click((e) => {
e.preventDefault();
var fd = $("#animal-form-input");
var files = $("#file")[0].files[0];
fd.append("file", files);
$.ajax({
url: "php_utility/ajax/admin-animal.php",
type: "post",
data: fd,
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
if (response === "allok") {
showModalError("Registrato Correttamente", "modalsuccess");
} else {
showModalError("Non Registrato Correttamente", "modalerror");
}
},
});
以及您在下面的代码中看到的方法。我被限制在没有插件的情况下这样做。我也在尝试使用,$.post()
但如果我理解正确,我必须使用$.ajax()
添加processData: false
来发送文件。
HTML
<form method="POST" action="" id="animal-form-insert" enctype="multipart/form-data">
<div class="span-1-of-2">
<label for="specie" class="label">Specie Animale:</label>
<input type="text" class="animal-input" id="specie" name="specie" required placeholder="Pavo cristatus">
<label for="an-name" class="label">Nome Comune:</label>
<input type="text" class="animal-input" id="an-name" name="an-name" required placeholder="pavone comune">
</div>
<div class="span-1-of-2">
<label for="biom" class="label">Bioma/Habitat:</label>
<select class="animal-input" name="biom" id="biom" required>
<option value="Savana">Savana</option>
<option value="Tundra">Tundra</option>
<option value="Pianura">Pianura</option>
</select>
<label for="zoo-zone" class="label">Zona Zoo:</label>
<select class="animal-input" name="zoo-zone" id="zoo-zone">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="F">F</option>
<option value="PN">PN</option>
</select>
</div>
<label for="animal-photo" class="label">Foto Animale:</label>
<input type="file" id="animal-photo" name="animal-photo" accept=".jpg,.jpeg.png" required>
<label for="aniaml-desc" class="label">Descrizione:</label>
<textarea class="animal-input-desc" name="animal-desc" id="animal-desc" required></textarea>
<button type="submit" name="animal-insert" id="animal-insert" class="btn btn-block">Aggiungi</button>
</form>
JS
$("#animal-insert").click((e) => {
e.preventDefault();
var formData = {
specie: $("#specie").val(),
anname: $("#an-name").val(),
biom: $("#biom").val(),
zoozone: $("#zoo-zone").val(),
animaldesc: $("#animal-desc").val(),
animalphoto: $("#animal-photo")[0].files[0],
submit: "submit",
};
console.log(formData);
$.ajax({
url: "php_utility/ajax/admin-animal.php",
type: "post",
data: JSON.stringify(formData),
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
if (response === "allok") {
showModalError("Registrato Correttamente", "modalsuccess");
} else {
showModalError("Non Registrato Correttamente", "modalerror");
}
},
});
});
PHP
<?php
error_log($_POST['specie']);
if (isset($_POST['specie'])) {
$animalspecie = $_POST['specie'];
$animalName = $_POST['anname'];
$animalBiom = $_POST['biom'];
$animalZone = $_POST['zoozone'];
$animalDesc = $_POST['animaldesc'];
$animalPhoto = $_FILES['animalphoto'];
$animalPhotoName = $animalPhoto['name'];
$photoTmp = $animalPhoto['tmp_name'];
$photoErr = $animalPhoto['error'];
$photoType = $animalPhoto['type'];
error_log("not here");
$formats = ["image/jpg", "image/jpeg", "image/png"];
require_once '../sql/utility.php'; //file with functions for db
require_once '../checks.php'; //file with some type checks
if (empty($animalspecie) || empty($animalName) || empty($animalBiom) || empty($animalZone) || empty($animalDesc) || empty($animalPhoto)) {
echo "emptyinput";
exit();
}
if (!preg_match('/[A-Z]+[a-z]+\s[a-z]+/', $animalspecie)) {
echo "invalidspecie";
exit();
}
if (!in_array($photoType, $formats)) {
echo "invalidformat";
exit();
}
if ($photoErr !== 0) {
echo "fileerror";
exit();
}
$tmpExtension = explode("/", $photoType);
$photoExtension = end($tmpExtension);
$photoNewName = preg_replace('/\s+/', '', $animalName) . preg_replace('/\s+/', '', $animalName) . "." . $photoExtension;
$photoDestination = "//resurces/images/animals/" . $photoNewName;
move_uploaded_file($photoTmp, $_SERVER['DOCUMENT_ROOT'] . $photoDestination);
$result = insertAnimal($conn, $animalspecie, $animalName, $animalBiom, $animalZone, $animalDesc);
echo $result;
}
解决方案
您应该创建一个new FormData()
并将您的表单值和文件附加到它,然后在data
(not body
) 参数中将其作为 'multipart/form-data' 发送。
$("#animal-insert").click((e) => {
e.preventDefault();
var formData = new FormData();
formData.append("specie", $("#specie").val())
formData.append("anname", $("#an-name").val())
formData.append("biom", $("#biom").val())
formData.append("zoozone", $("#zoo-zone").val())
formData.append("animaldesc", $("#animal-desc").val())
formData.append("animalphoto", $("#animal-photo")[0].files[0])
formData.append("submit", "submit")
$.ajax({
url: "php_utility/ajax/admin-animal.php",
method: "post",
data: formData,
cache: false,
mimeType: "multipart/form-data",
contentType: false,
processData: false,
success: function (response) {
console.log(response);
if (response === "allok") {
showModalError("Registrato Correttamente", "modalsuccess");
} else {
showModalError("Non Registrato Correttamente", "modalerror");
}
},
});
});
在 PHP 中,您的文件将在$_FILES
数组中可用,而其他数据将在$_POST
数组中。
有关 FormData 的更多信息:https ://developer.mozilla.org/en-US/docs/Web/API/FormData
推荐阅读
- css - 如何修改 bootstrap 4.5 tooltip css?
- sql - SQL 组数据在 90 秒的日期差内
- python - 虽然函数卡在 if-elif-else 的第一个块上
- java - 以最终意图启动 Activity 时应用程序崩溃
- html - 我如何让它像暗模式和亮模式一样切换到黑色或白色?
- spring-boot - QueuesNotAvailableException:无法为侦听器准备队列。队列不存在或代理不允许我们使用它
- bash - 如何在同一命令中同时使用变量和更改的变量
- python - 将数据从 JSON 文件转储到类变量并从类外部访问数据
- json - 如何获取 perl json 访问哈希参考
- php - 我可以使用 JQ fetch url 将数据传递给预定义的 PHP 类吗?