DEV Community

Horacio Rivero
Horacio Rivero

Posted on

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

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
    }
}
}) 
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
benjioe profile image
Benjioe • Edited

I think to upload file using fetch, you have to use a FormData.
But fetch is not able to track progress, for now you have to use XMLHttpRequest or a node package.