xhr.upload监控上传事件

绑定onprogress 事件必须使用 addEventListener 方式

xhr.upload.onprogress 上传事件

xhr.onprogress 下载事件

注意:
xhr.upload.addEventListener绑定必须放在xhr.send()之前
加了progress其实是发送了两次请求的

前台js

<body class="m-2">
  <label for="a" class="btn btn-primary">点击上传</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('上传开始')
        })
        
        xhr.upload.addEventListener('error', e => {
          l('上传失败')
        })

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

        xhr.upload.addEventListener('timeout', e => {
          l('由于预设时间到期,上传终止')
        })

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

        xhr.upload.addEventListener('loadend', e => {
          l('上传已经停止了')
        })

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

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

</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容