最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Streaming multipartform-data request with native fetch in Node.js? - Stack Overflow

programmeradmin1浏览0评论

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.

Share Improve this question edited Mar 20, 2023 at 23:28 danneu asked Mar 20, 2023 at 16:51 danneudanneu 9,5043 gold badges39 silver badges64 bronze badges 1
  • You might be interested in this: developer.chrome./articles/fetch-streaming-requests/… – Parzh Commented Apr 14, 2023 at 9:24
Add a ment  | 

1 Answer 1

Reset to default 6

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.', {
        method: 'POST',
        body: formData,
    })
}
发布评论

评论列表(0)

  1. 暂无评论