DEV Community

Jiri Spac
Jiri Spac

Posted on

1

How to send a file in form of a Buffer as a FormData in node.js

This is slightly modified excerpt from https://github.com/octet-stream/form-data#readme

import {Readable} from "stream"

import {FormData} from "formdata-node"

class BlobFromStream {
  #stream: Readable
  size: number

  constructor(stream: Readable, size: number) {
    this.#stream = stream
    this.size = size
  }


  stream() {
    return this.#stream
  }

  get [Symbol.toStringTag]() {
    return "Blob"
  }
}

const content = Buffer.from("Stream content")

const stream = new Readable({
  read() {
    this.push(content)
    this.push(null)
  }
})

const form = new FormData()

form.set("stream", new BlobFromStream(stream, content.length), "file.txt")

await fetch("https://httpbin.org/post", {method: "post", body: form})

Enter fullscreen mode Exit fullscreen mode

just in case anyone would be struggling with this same as me.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay