在 Javascript 中使用 Fetch API 上传文件并显示进度 [英] Upload file with Fetch API in Javascript and show progress

查看:57
本文介绍了在 Javascript 中使用 Fetch API 上传文件并显示进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Javascript 中使用 Fetch API将大文件上传到服务器.Fetch API 中是否有任何事件可用于跟踪上传进度?

I'm using Fetch API in Javascript to upload big file to server. Is there any event in Fetch API that I could use to track progress of upload?

推荐答案

不可能.原因在于 Fetch API 的工作方式.

This is NOT possible. The reason is the way the Fetch API works.

fetch 方法返回一个 Promise;Promise API 使用 then 方法,您可以将成功"和失败"回调附加到该方法.因此,您可以获得进度.

The fetch method returns a Promise; the Promise API uses a then method to which you can attach "success" and "failure" callbacks. Therefore, you can gain access to progress.

不过,不要失去希望!有一种解决方法可以解决问题(我在 Fetch 的 github 存储库中找到了它API):

Still, don't lose hope! There is a workaround that can do the trick (I found it on github repository of the Fetch API):

您可以将请求转换为流请求,然后在响应返回时只是文件内容的位数组.那么您需要收集所有数据,并在其结束时将其解码为您想要的文件

you can convert the request to a stream request and then when a response return is just a bitarray of the file content. then you need to collect all of the data and when its end decode it to the file you want

function consume(stream, total = 0) {
  while (stream.state === "readable") {
    var data = stream.read()
    total += data.byteLength;
    console.log("received " + data.byteLength + " bytes (" + total + " bytes in total).")
  }
  if (stream.state === "waiting") {
    stream.ready.then(() => consume(stream, total))
  }
  return stream.closed
}
fetch("/music/pk/altes-kamuffel.flac")
  .then(res => consume(res.body))
  .then(() => console.log("consumed the entire body without keeping the whole thing in memory!"))
  .catch((e) => console.error("something went wrong", e))

这篇关于在 Javascript 中使用 Fetch API 上传文件并显示进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆