通过Fetch API进度指示器

时间:2017-11-14 11:54:41

标签: javascript

我正在尝试捕获Fetch请求的进度,并使用它来更改进度条的宽度。我将ProgressEvent.lengthComputable看作是一个潜在的解决方案,但不确定它是否可以与Fetch API一起使用。

2 个答案:

答案 0 :(得分:1)

不检查错误(例如在try / catch等中)

const elStatus = document.getElementById('status');
function status(text) {
  elStatus.innerHTML = text;
}

const elProgress = document.getElementById('progress');
function progress({loaded, total}) {
  elProgress.innerHTML = Math.round(loaded/total*100)+'%';
}

async function main() {
  status('downloading with fetch()...');
  const response = await fetch('https://fetch-progress.anthum.com/30kbps/images/sunrise-baseline.jpg');
  const contentLength = response.headers.get('content-length');
  const total = parseInt(contentLength, 10);
  let loaded = 0;

  const res = new Response(new ReadableStream({
    async start(controller) {
      const reader = response.body.getReader();
      for (;;) {
        const {done, value} = await reader.read();
        if (done) break;
        loaded += value.byteLength;
        progress({loaded, total})
        controller.enqueue(value);
      }
      controller.close();
    },
  }));
  const blob = await res.blob();
  status('download completed')
  document.getElementById('img').src = URL.createObjectURL(blob);
}

main();
<div id="status">&nbsp;</div>
<h1 id="progress">&nbsp;</h1>
<img id="img" />

改编自here

答案 1 :(得分:0)

你可以使用axios

import axios from 'axios'
export async function uploadFile(file, cb) {
  const url = `//127.0.0.1:4000/profile`
  try {
    let formData = new FormData()
    formData.append("avatar", file)
    const data = await axios.post(url, formData, {
      onUploadProgress: (progressEvent) => {
        console.log(progressEvent)
        if (progressEvent.lengthComputable) {
          let percentComplete = progressEvent.loaded / progressEvent.total;
          if (cb) {
            cb(percentComplete)
          }
        }
      }
    })
    return data
  } catch (error) {
    console.error(error)
  }
}