HTML5 拖拽上传显示进度条

2017-09-03 1444 0

html部分:

  1. <div id="upload-box" class="jumbotron" style="text-align: center;border: 2px dashed #ff9163;">
  2. <h2>将文件拖动到此处上传</h2>
  3. </div>

JavaScript部分

  1. <script>
  2. $(function(){
  3. var box = document.getElementById("upload-box");
  4. $(document).on({
  5. dragenter: function(e){
  6. e.stopPropagation();
  7. e.preventDefault();
  8. },
  9. dragover: function(e){
  10. e.stopPropagation();
  11. e.preventDefault();
  12. box.innerHTML = "<h2>松开鼠标开始上传</h2>";
  13. },
  14. dragleave: function(e){
  15. e.stopPropagation();
  16. e.preventDefault();
  17. box.innerHTML = "<h2>拖拽到这里上传</h2>";
  18. },
  19. drop: function(e){
  20. e.stopPropagation();
  21. e.preventDefault();
  22. box.innerHTML = "<h2>上传中...</h2>";
  23. var files = e.originalEvent.dataTransfer.files;
  24. var xhr = new XMLHttpRequest();
  25. var formData = new FormData();
  26. for(var i = 0; i < files.length; i++){
  27. formData.append("myfile", files[i]);
  28. }
  29. xhr.upload.onprogress = function(e){
  30. if(e.lengthComputable){
  31. var precentage = Math.round((e.loaded * 100)/ e.total);
  32. box.innerHTML = "<h2>上传中(" + precentage + "%)...</h2>";
  33. }
  34. }
  35. xhr.onload = function(e){
  36. box.innerHTML = "<h2>上传成功,请刷新页面</h2>";
  37. }
  38. xhr.onerror = function(e){
  39. box.innerHTML = "<h2>上传失败</h2>";
  40. }
  41. xhr.open("post", "/upload", true);
  42. xhr.send(formData);
  43. }
  44. })
  45. })
  46. </script>

注意事项

xhr.upload.onprogress这几个监听必须写在xhr.open前面,否则进度更新事件在Chrome中不会触发。

如果使用原始的JavaScript代码box.ondrop = function(e){},files存在于e.dataTransfer.files中,在jQuery中则是e.originalEvent.dataTransfer.files