首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用ajax和php上传文件

使用AJAX和PHP上传文件的方法如下:

  1. 创建HTML表单:
代码语言:html
复制
<form id="upload_form" enctype="multipart/form-data">
 <input type="file" name="fileToUpload" id="fileToUpload">
 <button type="submit">上传文件</button>
</form>
  1. 使用JavaScript和AJAX发送文件:
代码语言:javascript
复制
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);
});
  1. 创建PHP文件处理程序(upload.php):
代码语言:php
复制
<?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上传文件,并且可以在不刷新页面的情况下上传文件。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券