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('', {
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.
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.', {
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.
- You might be interested in this: developer.chrome./articles/fetch-streaming-requests/… – Parzh Commented Apr 14, 2023 at 9:24
1 Answer
Reset to default 6Here'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.', {
method: 'POST',
body: formData,
})
}