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