xhr.upload監(jiān)控上傳事件

綁定onprogress 事件必須使用 addEventListener 方式

xhr.upload.onprogress 上傳事件

xhr.onprogress 下載事件

注意:
xhr.upload.addEventListener綁定必須放在xhr.send()之前
加了progress其實(shí)是發(fā)送了兩次請(qǐng)求的

前臺(tái)js

<body class="m-2">
  <label for="a" class="btn btn-primary">點(diǎn)擊上傳</label>
  <input id='a' name="file" type="file" accept="image/png, image/jpeg, video/*" style="display:none;" multiple='multiple'>
  <script>
    async function main() {

      const l = console.log
      let fileEle = document.querySelector('#a')
      fileEle.onchange = e => {
        let files = fileEle.files
        if(files.length === 0) return false;

        let data = new FormData()
        for(const file of files){
          data.append('files', file)
        }

        let xhr = new XMLHttpRequest()
        
        xhr.upload.addEventListener('progress', e => {
          if (e.lengthComputable) {
            var percentage = Math.round((e.loaded * 100) / e.total);
            l(`${percentage}%`)
          }
        })

        xhr.open('post', 'http://localhost:5000/upload')
        xhr.responseType = 'json'
        xhr.send(data)

        xhr.upload.addEventListener('loadstart', e => {
          l('上傳開(kāi)始')
        })
        
        xhr.upload.addEventListener('error', e => {
          l('上傳失敗')
        })

        xhr.upload.addEventListener('abort', e => {
          l('上傳終止')
        })

        xhr.upload.addEventListener('timeout', e => {
          l('由于預(yù)設(shè)時(shí)間到期,上傳終止')
        })

        xhr.upload.addEventListener('load', e => {
          l('上傳成功了')
        })

        xhr.upload.addEventListener('loadend', e => {
          l('上傳已經(jīng)停止了')
        })

        xhr.onload = () => {
          l(...xhr.response.imgsSrc);
        }

      }
    }
    main();
  </script>
</body>

</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容