Upload file using Fetch and calc the progress using readable streams not work as expected (Browser)

Viewed 767

I am trying to upload a file using fetch streams, I need can calculate the upload progress.

But on the server I receive an corrupt file of 0 bytes, I really don't know how to use the ReadableStreams feature, that is a really new feature.

Client (Browser)

const fileReadble = (reader) => new ReadableStream({
  start(controller) {
     return pump()
      function pump() {
        return reader.read().then(({ done, value }) => {
          if (done) {
              controller.close()
              return
          }
        
          controller.enqueue(value)
          return pump()
        })
      }
  }

const uploadVideo = async (file) => {
    const fileReader = file.stream().getReader()
    const response = await fetch('http://localhost:3005', { 
      method: 'POST',   
      body: fileReadble(fileReader),
    })
  
    if (!response.ok) {
      console.error(`unexpected response ${response.statusText}`)
      return
    }
}
}) 

Server (Node)

import http from 'node:http'
import { createWriteStream } from 'node:fs'

http
  .createServer((req) => {
    if (req.method !== 'POST') return
    req.pipe(createWriteStream('./video.mp4'))
  })
  .listen(3005)

Note: I am using tus-js-client on the server to upload videos to vimeo, this is for security reasons, I need to send the file using Fetch.

0 Answers
Related