• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

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

    发布者: 土豆服务器 | 发布时间: 2025-6-16 12:28| 查看数: 60| 评论数: 0|帖子模式

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

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

    2.1 HTML
    1. <div class="process-wrapper" id="processWrap">
    2. <div class="process-face"></div>
    3. <img class="close-icon" id="closeBtn" src="../../images/close.png" alt="">
    4. <div class="process">
    5.   <div class="process-inner" id="processInner" style="width:50%"></div>
    6.   <div class="process-value">
    7.    <span>提交中...</span>
    8.    <span id="process">0%</span>
    9.   </div>
    10. </div>
    11. </div>
    复制代码
    2.2 CSS样式
    1. /* 附件上传进度条 */
    2. .process-wrapper{
    3. -moz-user-select:none;
    4. position: fixed;
    5. left: 0;
    6. top: 0;
    7. bottom: 0;
    8. right: 0;
    9. z-index: 10000;
    10. display: none;
    11. }
    12. .process-face{
    13. width: 100%;
    14. height: 100%;
    15. background-color: #000;
    16. opacity: 0.7;
    17. position: fixed;
    18. }
    19. .close-icon{
    20. width: 26px;
    21. height: 26px;
    22. position: fixed;
    23. left: 50%;
    24. top: calc( 50% + 40px );
    25. transform: translate(-50%,-50%);
    26. }
    27. .process{
    28. width: 90%;
    29. height: 30px;
    30. background-color: #fff;
    31. border-radius: 30px;
    32. overflow: hidden;
    33. position: absolute;
    34. left: 50%;
    35. top: 50%;
    36. transform: translate(-50%,-50%);
    37. text-align: center;
    38. font-size: 14px;
    39. line-height: 30px;
    40. color: #999;
    41. }
    42. .process-inner{
    43. width: 100%;
    44. height: 30px;
    45. position: absolute;
    46. left: 0;
    47. top: 0;
    48. background-color: #0079C1;
    49. transition: 0.1s;
    50. z-index: -1;
    51. }
    复制代码
    2.3 JS
    1. (function(app, doc) {

    2. var $processWrap = document.getElementById("processWrap"),
    3. $closeBtn = document.getElementById("closeBtn"),
    4. xhr = new XMLHttpRequest();
    5. doc.addEventListener('netchange', onNetChange, false);
    6. function onNetChange() {
    7.   if ($processWrap.style.display != "none") {
    8.    $processWrap.style.display = "none";
    9.    xhr.abort();
    10.    mui.toast('网络中断请重试');
    11.   }
    12. }
    13. doSend: function() {
    14.    app.ajaxFile({  //封装好的ajax请求
    15.    url: "",
    16.    data: FormData,
    17.    xhr: xhr,
    18.    success: function(r) {
    19.     if (r == '1') {
    20.      mui.toast("保存成功");
    21.      // 上传成功逻辑处理
    22.     } else {
    23.      $processWrap.style.display = "none";
    24.      mui.toast(app.netError);
    25.     }
    26.    },
    27.    error: function(r) {
    28.     $processWrap.style.display = "none";
    29.    },
    30.    progress: function(e) {
    31.     if (e.lengthComputable) {
    32.      var progressBar = parseInt((e.loaded / e.total) * 100);
    33.      if (progressBar < 100) {
    34.       $progress.innerHTML = progressBar + "%";
    35.       $processInner.style.width = progressBar + "%";
    36.      }
    37.     }
    38.    },
    39.    timeout:function(){
    40.     $processWrap.style.display = "none";
    41.    }

    42.   });
    43. })
    44. mui.plusReady(function() {
    45.   $closeBtn.addEventListener("tap",function(){
    46.    setTimeout(function(){
    47.     $processWrap.style.display = "none";
    48.     xhr.abort();
    49.    }, 400);
    50.   })
    51. });
    52. })(app, document);
    复制代码
    三、app.js封装ajax请求
    1. var $ajaxCount = 0;

    2. window.app = {
    3. //ajaxFile超时时间
    4. fileTimeout: 180000,
    5. ajaxFile: function(option) {
    6. $ajaxCount++;
    7. var _ajaxCount = $ajaxCount;
    8. if (!option.error) {
    9.   option.error = ajaxError; // 请求失败提示
    10. }
    11. if (option.validateUserInfo == undefined) option.validateUserInfo = true;
    12. var xhr = option.xhr || new XMLHttpRequest();
    13. xhr.timeout = app.fileTimeout;
    14. xhr.open('POST', app.getItem(app.localKey.url) + option.url, true);
    15. xhr.onreadystatechange = function() {
    16.   if (xhr.readyState == 4 && xhr.status == 200) {
    17.    var r = xhr.responseText;
    18.    if (r) {
    19.     r = JSON.parse(r);
    20.    }
    21.    if (_ajaxCount == $ajaxCount) {
    22.     option.success && option.success(r);
    23.    }
    24.   }
    25. }
    26. xhr.upload.onprogress = function (e) {
    27.   option.progress(e);
    28. }
    29. xhr.onerror = function(e) {
    30.   option.error(e); // 添加 上传失败后的回调函数
    31. }
    32. xhr.ontimeout = function(e){
    33.   option.timeout(e);
    34.   app.closeWaiting();
    35.   $.toast("请求超时,请重试");
    36.   xhr.abort();
    37.   }
    38. xhr.send(option.data);
    39. },
    40. }
    复制代码
    拓展:后端NodeJS实现代码
    1. const express = require("express");
    2. const multer = require("multer");
    3. const expressStatic = require("express-static");
    4. const fs = require("fs");

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

    14. // 处理静态目录
    15. server.use(expressStatic(__dirname+"/www"))
    16. // 监听服务
    17. server.listen(8080, function(){
    18.   console.log("请使用浏览器访问 http://localhost:8080/")
    19. });
    复制代码
    到此这篇关于Html5 new XMLHttpRequest()监听附件上传进度的文章就介绍到这了,更多相关Html5 监听附件上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!

    来源:https://www.jb51.net/html5/760763.html
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表