当前位置:首页 > HTML5 文件上传

HTML5 文件上传

发布于 2018-04-08 阅读 767 次 Javascript HTML5
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>html5上传</title>
  6. <style>
  7. div{padding:20px;}
  8. </style>
  9. </head>
  10. <body>
  11. <input type="file" id="file" multiple />
  12. <div id="details"></div>
  13. <button onclick="showFile()">提交</button>
  14. <div><progress id="Progress" value="0" max="100" ></progress></div>
  15. <script type="text/javascript">
  16. function showFile () {
  17. var files,item,len,i,filename,filesize,type,dstr;
  18. var details = document.getElementById("details");
  19. files = document.getElementById("file").files;
  20. // console.log(files);
  21. for(i=0, len=files.length; i<len; i++){
  22. var s='';
  23. var oSpan = document.createElement("span");
  24. // console.log(oSpan)
  25. oSpan.innerHTML = (i+1)+'.->'+files[i].name+'文件大小:' + files[i].size;
  26. details.appendChild(oSpan);
  27. getFile(files[i]);
  28. }
  29. }
  30. //通过filereader接口获取文件
  31. function getFile(file){
  32. if(FileReader){
  33. var start = 0,end = 0,length = 1000;
  34. var fr = new FileReader();
  35. // fr.readAsText(file,[encoding]);//默认是utf-8编码
  36. // fr.readAsBinaryString(file); //二进制读取
  37. var readBlob = function(file,start,end){
  38. // alert(1)
  39. if(file.webkitSlice){
  40. var blob = file.webkitSlice(start, end);
  41. }else if(file.mozSlice){
  42. var blob = file.mozSlice(start, end);
  43. }else{
  44. var blob = file.slice(start, end);
  45. }
  46. fr.readAsDataURL(blob);
  47. };
  48. readBlob(file, start, end);
  49. // 读取中断的时候触发
  50. fr.onabort = function(){
  51. };
  52. // 出错时触发
  53. fr.onerror = function(){
  54. };
  55. //读取成功时触发
  56. fr.onload = function(e){
  57. if(end == file.size) return;
  58. console.log(file.name,start,end);
  59. var head = end;
  60. end = (start + length) > file.size ? (file.size) : (start + length);
  61. start = head;
  62. readBlob(file, start, end);
  63. };
  64. // 读取完成是触发,无论成功还是失败
  65. fr.onloadend = function(){
  66. };
  67. // 开始读取的时候触发
  68. fr.onloadstart = function(file,start,end){
  69. };
  70. // 读取过程中触发
  71. fr.onprogress = function(e){
  72. var pro = document.getElementById("Progress"),
  73. percent = end/file.size;
  74. console.log(e,percent)
  75. // console.log(e)
  76. // console.log(e.loaded);
  77. };
  78. }else{
  79. alert("Your browser doesn't support FileReader");
  80. }
  81. }
  82. </script>
  83. </body>
  84. </html>