php+html5+ajax实现上传图片的方法
author:一佰互联 2019-04-27   click:198

本文实例讲述了php+html5+ajax实现上传图片的方法。分享给大家供大家参考,具体如下:

<?php
if (isset($_POST["upload"])) {
  var_dump($_FILES);
  move_uploaded_file($_FILES["upfile"]["tmp_name"], "up_tmp/".time().".dat");
  //header("location: test.php");
  exit;
}
?>

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <title>HTML5 Ajax Uploader</title>
  <script src="jquery-2.1.1.min.js"></script>
</head>
<body>
<p><input type="file" id="upfile"></p>
<p><input type="button" id="upJS" value="用原生JS上传"></p>
<p><input type="button" id="upJQuery" value="用jQuery上传"></p>
<script>
  /*原生JS版*/
  document.getElementById("upJS").onclick = function() {
    /* FormData 是表单数据类 */
    var fd = new FormData();
    var ajax = new XMLHttpRequest();
    fd.append("upload", 1);
    /* 把文件添加到表单里 */
    fd.append("upfile", document.getElementById("upfile").files[0]);
    ajax.open("post", "test.php", true);
    ajax.onload = function () {
      console.log(ajax.responseText);
    };
    ajax.send(fd);
  }
  /* jQuery 版 */
  $("#upJQuery").on("click", function() {
    var fd = new FormData();
    fd.append("upload", 1);
    fd.append("upfile", $("#upfile").get(0).files[0]);
    $.ajax({
      url: "test.php",
      type: "POST",
      processData: false,
      contentType: false,
      data: fd,
      success: function(d) {
        console.log(d);
      }
    });
  });
</script>
</body>
</html>

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php文件操作总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。