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


Posted in HTML / CSS onJanuary 14, 2021

本文主要介绍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 监听附件上传内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章,希望大家以后多多支持三水点靠木!

HTML / CSS 相关文章推荐
css3 伪元素和伪类选择器详解
Sep 04 HTML / CSS
CSS3实现滚动条动画效果代码分享
Aug 03 HTML / CSS
纯CSS3单页切换导航菜单界面设计的简单实现
Aug 16 HTML / CSS
详解css3中 text-fill-color属性
Jul 08 HTML / CSS
CSS3动画特效在活动页中的应用
Jan 21 HTML / CSS
使用html5+css3来实现slider切换效果告别javascript+css
Jan 08 HTML / CSS
HTML5 video标签(播放器)学习笔记(一):使用入门
Apr 24 HTML / CSS
基于MUI框架使用HTML5实现的二维码扫描功能
Mar 01 HTML / CSS
使用canvas来完成线性渐变和径向渐变的功能的方法示例
Jul 25 HTML / CSS
canvas实现手机的手势解锁的步骤详细
Mar 16 HTML / CSS
css让页脚保持在底部位置的四种方案
Jul 23 HTML / CSS
CSS 鼠标点击拖拽效果的实现代码
Dec 24 HTML / CSS
HTML5 canvas实现的静态循环滚动播放弹幕
Jan 05 #HTML / CSS
Html5+CSS3+EL表达式问题小结
Dec 19 #HTML / CSS
前端使用canvas生成盲水印的加密解密的实现
Dec 16 #HTML / CSS
简洁自适应404页面HTML好看的404源码
Dec 16 #HTML / CSS
移动端HTML5开发神器之vconsole详解
Dec 15 #HTML / CSS
如何查看浏览器对html5的支持情况
Dec 15 #HTML / CSS
如何使用canvas绘制可移动网格的示例代码
Dec 14 #HTML / CSS
You might like
php实现在多维数组中查找特定value的方法
2015/07/29 PHP
微信支付开发发货通知实例
2016/07/12 PHP
如何通过View::first使用Laravel Blade的动态模板详解
2017/09/21 PHP
ThinkPHP实现的rsa非对称加密类示例
2018/05/29 PHP
ThinkPHP5.0多个文件上传后找不到临时文件的修改方法
2018/07/30 PHP
PHP实现简单的协程任务调度demo示例
2020/02/01 PHP
ExtJs中简单的登录界面制作方法
2010/08/19 Javascript
网页中表单按回车就自动提交的问题的解决方案
2014/11/03 Javascript
jquery弹出遮掩层效果【附实例代码】
2016/04/28 Javascript
JavaScript中访问id对象 属性的方式访问属性(实例代码)
2016/10/28 Javascript
javascript 操作cookies详解及实例
2017/02/22 Javascript
react-native之ART绘图方法详解
2017/08/08 Javascript
Javascript中toFixed计算错误(依赖银行家舍入法的缺陷)解决方法
2017/08/22 Javascript
jQuery第一次运行页面默认触发点击事件的实例
2018/01/10 jQuery
Vue的土著指令和自定义指令实例详解
2018/02/04 Javascript
微信小程序支付PHP代码
2018/08/23 Javascript
Vue瀑布流插件的使用示例
2018/09/19 Javascript
CKeditor富文本编辑器使用技巧之添加自定义插件的方法
2019/06/14 Javascript
vue实现匀速轮播效果
2020/06/29 Javascript
python 数据加密代码
2008/12/24 Python
pyqt和pyside开发图形化界面
2014/01/22 Python
使用PDB简单调试Python程序简明指南
2015/04/25 Python
利用Python如何批量更新服务器文件
2018/07/29 Python
windows下搭建python scrapy爬虫框架步骤
2018/12/23 Python
python标准库sys和OS的函数使用方法与实例详解
2020/02/12 Python
python 基于opencv 实现一个鼠标绘图小程序
2020/12/11 Python
Keras保存模型并载入模型继续训练的实现
2021/02/20 Python
德国BA保镖药房韩文网:kr.ba.de
2017/09/04 全球购物
意大利中国电子产品购物网站:Geekmall.com
2019/09/30 全球购物
美国购物网站:Clickhere2shop
2021/01/28 全球购物
综合素质的自我鉴定
2013/10/07 职场文书
初二物理教学反思
2014/01/29 职场文书
进步之星获奖感言
2014/02/22 职场文书
2015年行政执法工作总结
2015/05/23 职场文书
银行资信证明
2015/06/17 职场文书
2016护理专业求职自荐书
2016/01/28 职场文书