Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming multipart/form-data request with native fetch in Node.js?

I'm trying to stream a file to an API using a multipart/form-data request with native fetch in Node.js.

Here's how you can upload the file after reading the whole file into memory:

const { readFile } = require('fs/promises')

async function upload() {
    const formData = new FormData()
    formData.append('user_id', 42)
    formData.append('audio', new Blob([await readFile('./music.mp3')]))

    const response = await fetch('http://api.example.com', {
        method: 'POST',
        body: formData,
    })
}

This works.

However, is there a way to upload the file without reading it entirely into memory with something like fs.createReadStream()?

For example, something like this would be nice if it worked:

formData.append('audio', fs.createReadStream('./music.mp3'))

It seems like libraries like node-fetch and request support this, but I'd like to do it natively if possible.

like image 235
danneu Avatar asked Sep 02 '25 14:09

danneu


1 Answers

Here's how you'd modify the code above to stream a file upload using native FormData and fetch:

const { createReadStream } = require('fs')

async function upload() {
    const formData = new FormData()
    formData.append('user_id', 42)
    formData.set('audio', {
        [Symbol.toStringTag]: 'File',
        name: 'music.mp3',
        stream: () => createReadStream('./music.mp3'),
    })

    const response = await fetch('http://api.example.com', {
        method: 'POST',
        body: formData,
    })
}
like image 173
danneu Avatar answered Sep 05 '25 03:09

danneu