使用 javascript 上传一组 blob 并在 Node.js 上处理它们

Uploading an array of blobs with javascript and handling them on Node.js

我正在尝试通过发送分块上传来解决 Cloudflare 的 100mb 上传限制。但是我似乎无法弄清楚如何真正开始发送分块数据。假设我有 100 个要发送到服务器的 blob,我要流式传输它们吗?服务器如何判断连续的请求彼此相关?

到目前为止,这是我的代码:

getChunks(file) {
  const divideBy = 1 * 1024 * 1024
  const availableDivisions = Math.ceil(file.size / divideBy)
  let currentSlice = 0

  const chunks = Array(availableDivisions)
    .fill()
    .map((iteration, index) => {
      const nextDivision = divideBy * (index + 1)
      const chunk = file.slice(currentSlice, nextDivision, file.type)

      currentSlice = nextDivision

      return chunk
    })

  return chunks
}

sendChunk(blob) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()

    xhr.open('POST', 'http://localhost:4080/test', true)
    xhr.setRequestHeader('Content-type', blob.type)

    xhr.onreadystatechange = () => {
      if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
        resolve()
      }
    }

    xhr.send(blob)
  })
}

uploadChunked(file) {
  const chunks = this.getChunks(file)

  let iteration = 0

  const upload = chunk => {
    let nextIteration = iteration + 1
    let nextChunk = chunks[nextIteration]

    this.sendChunk(chunk).then(() => {
      if (nextChunk) {
        iteration = nextIteration
        upload(nextChunk)
      }
    })
  }

  upload(chunks[0])
}

所以这工作正常,上传请求正确完成。我的问题是弄清楚服务器应该如何告诉所有这些连续的请求都指向一个文件。我在网上看过,我对这部分感到非常困惑。

你不能。 100 MB(或 X MB)不是每个请求的限制。

这是每个文件的限制。换句话说,如果你将它们分块,那么每个块最终都会成为服务器上的一个文件。

您可以像现在一样分几块上传它们,并提供额外的 script 以帮助您的用户稍后在客户端将它们拼接起来。

我已经使用 Tus protocol. 解决了我的问题 现在我的服务器可以接受分块(和可恢复)上传,而且 Cloudflare 不会抱怨。