如何克服因使用 AJAX (axios) 上传大文件而导致的浏览器延迟?

How do I overcome browser lag because of large file upload with AJAX (axios)?

我在前端使用 axios 实现了一个简单的多文件上传功能,ReactJS 用于 AJAX 请求。

const FileUploader = () => {

  const uploadFiles = files => {

    const formData = new FormData();
    files.forEach( file => {
      formData.append("files", file );
    })

    axios
    ({
      method: "POST",
      url: '...',
      data: formData,
      headers: { "Content-Type": "multipart/form-data", },
      onUploadProgress: e => console.log(e.loaded, e.total)
    })
    .then(( response ) => console.log( response ))
    .catch(( error )   => console.error( error ))
  }

  return (
   
    <input type="file" onChange={ e => uploadFiles( e.target.files ) } />

  )
}

我注意到在一次上传大文件或多个文件时,不仅是浏览器而且我的 OS 似乎都滞后。

在寻找解决方法时,我了解到需要使用 Streams API 通过网络逐块而不是一次完整地发送文件来解决此问题。

https://developer.mozilla.org/en-US/docs/Web/API/Streams_API

The Streams API allows JavaScript to programmatically access streams of data received over the network and process them as desired by the developer.

https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams

https://developer.mozilla.org/en-US/docs/Web/API/WritableStream

但是,我在 Internet 上看到的关于此主题的资源很少,这可能是因为 Streams API 是一个相对较新的 Web 介绍,仍处于实验阶段。

有很多文章解释了后端的实现,但在前端却很少。

我从哪里开始?代码可能是什么样的?

请注意,流针对的是 reading/processing 客户端上的文件,而不是用于上传。

With Streams being available to JavaScript, this all changes — you can now start processing raw data with JavaScript bit by bit as soon as it is available on the client-side, without needing to generate a buffer, string, or blob.

但是,您可以使用 XHR 实现分块上传。有几个库支持它。

对于 React,有 react-uploady. Check out its chunked upload support. It also supports resumable uploads (Tus) 用于同样实现协议的服务器