admin管理员组文章数量:1416081
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,
})
}
本文标签: javascriptStreaming multipartformdata request with native fetch in NodejsStack Overflow
版权声明:本文标题:javascript - Streaming multipartform-data request with native fetch in Node.js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745244562a2649497.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论