App下載

在Html5中怎么監(jiān)聽(tīng)附件上傳進(jìn)度?通過(guò)newXMLHttpRequest()實(shí)現(xiàn)監(jiān)聽(tīng)案例分享!

猿友 2021-07-30 13:42:44 瀏覽數(shù) (1770)
反饋

今天小編來(lái)和大家講講有關(guān)于:“在Html5中怎么監(jiān)聽(tīng)附件上傳進(jìn)度?”這方面的相關(guān)內(nèi)容,希望小編的分享對(duì)大家的學(xué)習(xí)有所幫助!

一、存在問(wèn)題

經(jīng)測(cè)試發(fā)現(xiàn),new XMLHttpRequest()在附件上傳請(qǐng)求中,WIFI關(guān)閉切4G上傳,上傳進(jìn)度不會(huì)持續(xù);4G不關(guān)閉打開(kāi)WIFI會(huì)繼續(xù)上傳,但等待時(shí)間過(guò)長(zhǎng),實(shí)際上是4G在上傳,倘若關(guān)閉4G網(wǎng)絡(luò),上傳進(jìn)度終止。

二、相關(guān)代碼

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樣式

/* 附件上傳進(jìn)度條 */
.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('網(wǎng)絡(luò)中斷請(qǐng)重試');
  }
 }
 doSend: function() {
   app.ajaxFile({  //封裝好的ajax請(qǐng)求 
   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請(qǐng)求

var $ajaxCount = 0;

window.app = {
 //ajaxFile超時(shí)時(shí)間
 fileTimeout: 180000,
 ajaxFile: function(option) {
 $ajaxCount++; 
 var _ajaxCount = $ajaxCount;
 if (!option.error) {
  option.error = ajaxError; // 請(qǐng)求失敗提示
 }
 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); // 添加 上傳失敗后的回調(diào)函數(shù)
 }
 xhr.ontimeout = function(e){
  option.timeout(e);
  app.closeWaiting();
  $.toast("請(qǐng)求超時(shí),請(qǐng)重試");
  xhr.abort();
  }
 xhr.send(option.data);
},
}

拓展:后端NodeJS實(shí)現(xiàn)代碼

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請(qǐng)求
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})
  })
})

// 處理靜態(tài)目錄
server.use(expressStatic(__dirname+"/www"))
// 監(jiān)聽(tīng)服務(wù)
server.listen(8080, function(){
  console.log("請(qǐng)使用瀏覽器訪問(wèn) http://localhost:8080/")
});

以上就是有關(guān)于:“在Html5中怎么監(jiān)聽(tīng)附件上傳進(jìn)度?”這方面的相關(guān)內(nèi)容分享,當(dāng)然對(duì)于html5這方面的相關(guān)知識(shí)不僅僅只有如此,有感興趣的小伙伴們還可以在W3Cschool中進(jìn)行系統(tǒng)的學(xué)習(xí)! 


0 人點(diǎn)贊