在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

JavaScript异步拖拽上传文件

2016-12-20 13:16| 发布者: zhangjf| 查看: 524| 评论: 0

摘要: upload.html !DOCTYPE html !-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the edit ...
upload.html
  1. <!DOCTYPE html>
  2. <!--
  3. To change this license header, choose License Headers in Project Properties.
  4. To change this template file, choose Tools | Templates
  5. and open the template in the editor.
  6. -->
  7. <html>
  8. <head>
  9. <title>TODO supply a title</title>
  10. <meta charset="UTF-8">
  11. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  12. <style>
  13. #box{
  14. width:150px;height: 150px;border: 1px solid red;
  15. }
  16. </style>
  17. <script type="text/javascript" src="XMLhttpReuest.js"></script>
  18. <script>
  19. window.onload = function () {
  20. var box = document.getElementById('box');
  21. box.ondragenter = function (e) {
  22. e.preventDefault();
  23. }
  24. box.ondragover = function (e) {
  25. e.preventDefault();
  26. }
  27. box.ondragleave = function (e) {
  28. e.preventDefault();
  29. }
  30. box.ondrop = function (e) {
  31. e.preventDefault();
  32. var file = e.dataTransfer.files[0];
  33. var formData = new FormData();
  34. formData.append('aa', file);
  35. var xml = ajaxFunction();
  36. xml.open("post", './upload.php', true);
  37. xml.send(formData);
  38. xml.onreadystatechange = function () {
  39. if (xml.readyState == 4 && xml.status == 200) {
  40. var flag = xml.responseText;
  41. console.log(flag);
  42. if (flag == 1) {
  43. // box.innerHTML="上传成功";
  44. alert('上传成功');
  45. }
  46. }
  47. }
  48. }
  49. }
  50. </script>
  51. </head>
  52. <body>
  53. <div id="box">
  54. 请拖入上传的文件
  55. </div>
  56. </body>
  57. </html>
复制代码
upload.php
  1. <?php
  2. header("Content-Type:text/html;charset=UTF-8");
  3. if(is_uploaded_file($_FILES['aa']['tmp_name'])){
  4. move_uploaded_file($_FILES['aa']['tmp_name'], "./".iconv("UTF-8", "GBK", $_FILES['aa']['name']));
  5. echo '1';
  6. }
复制代码
XMLhttpReuest.js
  1. function ajaxFunction()
  2. {
  3. var xmlHttp;
  4. try
  5. {
  6. // Firefox, Opera 8.0+, Safari
  7. xmlHttp=new XMLHttpRequest();
  8. }
  9. catch (e)
  10. {
  11. // Internet Explorer
  12. try
  13. {
  14. xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  15. }
  16. catch (e)
  17. {
  18. try
  19. {
  20. xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  21. }
  22. catch (e)
  23. {
  24. alert("您的浏览器不支持AJAX!");
  25. return false;
  26. }
  27. }
  28. }
  29. return xmlHttp;
  30. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 17:14

Copyright 2015-2025 djqfx

返回顶部