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.
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,
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With