欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Html5 new XMLHttpRequest()监听附件上传进度

程序员文章站 2022-03-04 09:56:56
Html5 new XMLHttpRequest()监听附件上传进度这篇文章主要介绍了Html5 new XMLHttpRequest()监听附件上传进度,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 21-01-14...

本文主要介绍new xmlhttprequest()监听附件上传进度,解决优化loading长时间加载,用户等待问题

一、存在问题

经测试发现,new xmlhttprequest()在附件上传请求中,wifi关闭切4g上传,上传进度不会持续;4g不关闭打开wifi会继续上传,但等待时间过长,实际上是4g在上传,倘若关闭4g网络,上传进度终止。

二、相关代码

2.1 html

<div class="process-wrapper" id="processwrap">
 <div class="process-face"></div>
 <img class="close-icon" id="closebtn" src="../../images/close.png" alt="">
 <div class="process">
  <div class="process-inner" id="processinner" style="width:50%"></div>
  <div class="process-value">
   <span>提交中...</span> 
   <span id="process">0%</span>
  </div>
 </div>
</div>

2.2 css样式

/* 附件上传进度条 */
.process-wrapper{
 -moz-user-select:none;
 position: fixed;
 left: 0;
 top: 0;
 bottom: 0;
 right: 0;
 z-index: 10000;
 display: none;
}
.process-face{
 width: 100%;
 height: 100%;
 background-color: #000;
 opacity: 0.7;
 position: fixed;
}
.close-icon{
 width: 26px;
 height: 26px;
 position: fixed;
 left: 50%;
 top: calc( 50% + 40px );
 transform: translate(-50%,-50%);
}
.process{
 width: 90%;
 height: 30px;
 background-color: #fff;
 border-radius: 30px;
 overflow: hidden;
 position: absolute;
 left: 50%;
 top: 50%;
 transform: translate(-50%,-50%);
 text-align: center;
 font-size: 14px;
 line-height: 30px;
 color: #999;
}
.process-inner{
 width: 100%;
 height: 30px;
 position: absolute;
 left: 0;
 top: 0;
 background-color: #0079c1;
 transition: 0.1s;
 z-index: -1;
}

2.3 js

(function(app, doc) {
 
 var $processwrap = document.getelementbyid("processwrap"),
 $closebtn = document.getelementbyid("closebtn"),
 xhr = new xmlhttprequest();
 doc.addeventlistener('netchange', onnetchange, false);
 function onnetchange() {
  if ($processwrap.style.display != "none") {
   $processwrap.style.display = "none";
   xhr.abort();
   mui.toast('网络中断请重试');
  }
 }
 dosend: function() {
   app.ajaxfile({  //封装好的ajax请求 
   url: "",
   data: formdata,
   xhr: xhr,
   success: function(r) {
    if (r == '1') {
     mui.toast("保存成功");
     // 上传成功逻辑处理
    } else {
     $processwrap.style.display = "none";
     mui.toast(app.neterror);
    }
   },
   error: function(r) {
    $processwrap.style.display = "none";
   },
   progress: function(e) {
    if (e.lengthcomputable) {
     var progressbar = parseint((e.loaded / e.total) * 100);
     if (progressbar < 100) {
      $progress.innerhtml = progressbar + "%";
      $processinner.style.width = progressbar + "%";
     }
    }
   },
   timeout:function(){
    $processwrap.style.display = "none";
   }

  });
 })
 mui.plusready(function() {
  $closebtn.addeventlistener("tap",function(){
   settimeout(function(){
    $processwrap.style.display = "none";
    xhr.abort();
   }, 400);
  })
 });
})(app, document);

三、app.js封装ajax请求

var $ajaxcount = 0;

window.app = {
 //ajaxfile超时时间
 filetimeout: 180000,
 ajaxfile: function(option) {
 $ajaxcount++; 
 var _ajaxcount = $ajaxcount;
 if (!option.error) {
  option.error = ajaxerror; // 请求失败提示
 }
 if (option.validateuserinfo == undefined) option.validateuserinfo = true;
 var xhr = option.xhr || new xmlhttprequest();
 xhr.timeout = app.filetimeout;
 xhr.open('post', app.getitem(app.localkey.url) + option.url, true);
 xhr.onreadystatechange = function() {
  if (xhr.readystate == 4 && xhr.status == 200) {
   var r = xhr.responsetext;
   if (r) {
    r = json.parse(r);
   }
   if (_ajaxcount == $ajaxcount) {
    option.success && option.success(r);
   }
  }
 }
 xhr.upload.onprogress = function (e) {
  option.progress(e);
 }
 xhr.onerror = function(e) {
  option.error(e); // 添加 上传失败后的回调函数
 }
 xhr.ontimeout = function(e){
  option.timeout(e);
  app.closewaiting();
  $.toast("请求超时,请重试");
  xhr.abort();
  }
 xhr.send(option.data);
},
}

拓展:后端nodejs实现代码

const express = require("express");
const multer = require("multer");
const expressstatic = require("express-static");
const fs = require("fs");

let server = express();
let upload = multer({ dest: __dirname+'/uploads/' })
// 处理提交文件的post请求
server.post('/upload_file', upload.single('file'), function (req, res, next) {
  console.log("file信息", req.file);
  fs.rename(req.file.path, req.file.path+"."+req.file.mimetype.split("/").pop(), ()=>{
    res.send({status: 1000})
  })
})

// 处理静态目录
server.use(expressstatic(__dirname+"/www"))
// 监听服务
server.listen(8080, function(){
  console.log("请使用浏览器访问 http://localhost:8080/")
});

到此这篇关于html5 new xmlhttprequest()监听附件上传进度的文章就介绍到这了,更多相关html5 监听附件上传内容请搜索以前的文章或继续浏览下面的相关文章,希望大家以后多多支持!