HLJ 发布于
2022-10-02 11:10:49
26阅读

JavaScript new XMLHttpRequest() 获取文件的大小和文件加载进度条

https://zinoui.com/blog/ajax-request-progress-bar

<template>
  <div style="padding:20px">
    <div @click="download">加载文件</div>
    <progress id="progress" value="" max=""></progress>
    <div id="progressBar_value"></div>
    <div id="progressBar_max"></div>
  </div>
</template>

<script>
export default {
  name: 'Home',
  data() {
    return ({
      isSHow: false
    })
  },
  methods: {
    download() {
      var progressBar = document.getElementById("progress");
      var progressBar_value = document.getElementById("progressBar_value");
      var progressBar_max = document.getElementById("progressBar_max");

      var xhr = new XMLHttpRequest();
      xhr.open("GET", "/good4/1.jpg?" + Math.floor(Math.random() * 99999), true);
      xhr.responseType = "text";
      xhr.onprogress = function (e) {
        console.log(e)
        if (e.lengthComputable) {
          progressBar.max = e.total;
          progressBar.value = e.loaded;
          progressBar_value.innerHTML = `${(e.loaded / 1024 / 1024).toFixed(3)}MB`;
          progressBar_max.innerHTML = `${(e.total / 1024 / 1024).toFixed(3)}MB`;
        }
      };
      xhr.onloadstart = function (e) {
        progressBar.value = 0;
      };
      xhr.onloadend = function (e) {
        progressBar.value = e.loaded;
      };
      xhr.send(null);
    }
  }
}
</script>
当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2022-10-02/606.html
最后生成于 2024-06-22 12:07:23
此内容有帮助 ?
0