【发布时间】:2020-09-30 19:01:48
【问题描述】:
我完全迷路了。
我尝试在 PHP 中制作一些图像上传功能,一切正常。因为我不希望重新加载整个页面,所以在上传文件时我想将 AJAX 与 Jquery 一起使用,通过 POST 将表单内容(图像)发送到像 upload.php 这样带有隐藏 ajax 请求的文件。
无论我尝试什么都不可能用 formData() 发送任何东西。我复制并粘贴了几个示例代码,尝试更改代码,当我使用 formData() 时没有任何反应。
使用 Jquery / Ajax 的正常请求,使用 POST 可以正常工作。
这是我上次使用的代码示例..
我的 XamPP 是否配置错误,或者是什么原因导致 Google 的脚本、教程页面等都无法正常工作?
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="jquery.min.js"></script>
<form id="Test" action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
<button id="Knopf">Knopf</button>
<div id="Disp">fghfgh</div>
</body>
<script>
$(document).ready(function(){
$("#Knopf").click(function(){
var formData = new FormData(Test);
$.ajax({
url : "uploadtest2.php",
type : "POST",
data : formData,
cache : false,
contentType : false,
processType : false,
success : function() {
$("#Disp").html(result);
}
});
});
});
</script>
</html>
<?php
$target_dir = "Media/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
【问题讨论】:
-
在这一行中:
var formData = new FormData(Test);Test定义在哪里? -
@Twisty
<form id="Test" ...>。元素 ID 也是全局变量。
标签: javascript php html jquery ajax