0
我已经尝试了几种变化(基于文章和其他SO论坛),以使其起作用,并且我缩小了事实,即当我尝试将数据发送将数据形成我的PHP脚本。当我回显$ _FILES [“file”] [“name”]时,它是空的。使用Ajax上传文件
我测试过了,我的ajax和php脚本已连接,因为我可以返回一些数据,只是没有任何表单数据。这显然导致文件没有被上传。
我当前的代码是在参照本论坛(lee8oi的答案): jQuery Ajax File Upload 我开始了一个新的论坛,因为这个问题是6年前问。
HTML:
<form id="signUpForm" name="signUpForm" action="../functions/newUser.php" method="post">
<input type="file" class="su_photo" name="file" id="user-photo">
<input type="submit" id="sign-up" type="button" class="btn btn-primary btn-sm pull-right" value="Get Started">
</form>
JS:
$('#signUpForm').on('submit',function(){
var fd = new FormData($('#signUpForm'));
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "../../functions/newUser.php",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
console.log("PHP Output:");
console.log(data);
});
return false;
});
PHP:
if ($_POST["label"]) {
$label = $_POST["label"];
}
$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"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$filename = $label.$_FILES["file"]["name"];
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("uploads/" . $filename)) {
echo $filename . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $filename);
echo "Stored in: " . "uploads/" . $filename;
}
}
} else {
echo $_FILES["file"]["name"];
}
这工作完美!非常感谢! – BDeGiglio
好的答案,我upvoted,因为比我更好。你钉了它。 ;) –
没问题,谢谢。 – Mikey