当前位置:Gxlcms > PHP教程 > php+html5+ajax实现上传图片的方法

php+html5+ajax实现上传图片的方法

时间:2021-07-01 10:21:17 帮助过:6人阅读

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

  1. <?php
  2. if (isset($_POST['upload'])) {
  3. var_dump($_FILES);
  4. move_uploaded_file($_FILES['upfile']['tmp_name'], 'up_tmp/'.time().'.dat');
  5. //header('location: test.php');
  6. exit;
  7. }
  8. ?>
  1. <!doctype html>
  2. <html lang="zh">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>HTML5 Ajax Uploader</title>
  6. <script src="jquery-2.1.1.min.js"></script>
  7. </head>
  8. <body>
  9. <p><input type="file" id="upfile"></p>
  10. <p><input type="button" id="upJS" value="用原生JS上传"></p>
  11. <p><input type="button" id="upJQuery" value="用jQuery上传"></p>
  12. <script>
  13. /*原生JS版*/
  14. document.getElementById("upJS").onclick = function() {
  15. /* FormData 是表单数据类 */
  16. var fd = new FormData();
  17. var ajax = new XMLHttpRequest();
  18. fd.append("upload", 1);
  19. /* 把文件添加到表单里 */
  20. fd.append("upfile", document.getElementById("upfile").files[0]);
  21. ajax.open("post", "test.php", true);
  22. ajax.onload = function () {
  23. console.log(ajax.responseText);
  24. };
  25. ajax.send(fd);
  26. }
  27. /* jQuery 版 */
  28. $('#upJQuery').on('click', function() {
  29. var fd = new FormData();
  30. fd.append("upload", 1);
  31. fd.append("upfile", $("#upfile").get(0).files[0]);
  32. $.ajax({
  33. url: "test.php",
  34. type: "POST",
  35. processData: false,
  36. contentType: false,
  37. data: fd,
  38. success: function(d) {
  39. console.log(d);
  40. }
  41. });
  42. });
  43. </script>
  44. </body>
  45. </html>

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

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

人气教程排行