使用AJAX和PHP上传文件的方法如下:
<form id="upload_form" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<button type="submit">上传文件</button>
</form>
document.getElementById("upload_form").addEventListener("submit", function(e) {
e.preventDefault();
var formData = new FormData(this);
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.send(formData);
});
<?php
$target_dir = "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 "文件是一张图片 - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "文件不是一张图片。";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "文件已经存在。";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "非法的文件格式。";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "文件上传失败。";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "文件 ". basename( $_FILES["fileToUpload"]["name"]). " 已经上传成功。";
} else {
echo "文件上传出现错误。";
}
}
?>
这个方法将使用AJAX和PHP上传文件,并且可以在不刷新页面的情况下上传文件。
领取专属 10元无门槛券
手把手带您无忧上云