A modern web streams compatible "multipart/form-data" encoder. Inspired by https://github.com/form-data/form-data but simplified and updated to only use modern web standards. Unlike the built in FormData object, this implementation can support full streaming, where the data being uploaded is never fully loaded into memory as a Blob.
import FormDataWebStream from "form-data-web-stream"
const sourceRes = await fetch("https://example.com/source")
if (!sourceRes.ok) {
throw new Error("Fetch failed: " + (await sourceRes.text()))
}
const data = new FormDataWebStream()
data.appendString("my-field", "hello world")
data.appendStream("my-file", sourceRes.body, {
contentType: "text/plain",
filename: "sample-file.txt",
// You only need to specify `byteLength` if you plan to call `getByteLength` later
byteLength: parseInt(sourceRes.headers.get("content-length"), 10),
})
const response = await fetch("https://example.com/destination", {
method: "POST",
headers: {
"Content-Length": `${data.getByteLength()}`,
"Content-Type": data.getContentTypeHeader(),
},
body: data.toStream(),
duplex: "half",
})
console.log(await response.text())This library only uses Web streams, so node.js streams need to be converted using Readable.toWeb before passing them into this library.
import { createReadStream } from "fs"
import { Readable } from "stream"
import FormDataWebStream from "form-data-web-stream"
const data = new FormDataWebStream()
data.appendString("my-field", "hello world")
data.appendStream("my-file", Readable.toWeb(createReadStream("sample-file.txt")), {
contentType: "text/plain",
filename: "sample-file.txt",
})
const response = await fetch("https://example.com/destination", {
method: "POST",
headers: {
"Content-Type": data.getContentTypeHeader(),
},
body: data.toStream(),
duplex: "half",
})
console.log(await response.text())Append a string value to the form data.
Append a binary value to the form data.
Append a stream to the form data. Make sure you specify options.byteLength if you want to later call .getByteLength().
Returns true if a byte length is available. This will be false if any calls to appendStream did not include a byteLength option.
Returns the byte length of the entire stream, if available. This will throw an error if any calls to appendStream did not include a byteLength option.
Returns the header to use as the Content-Type in your request.
Returns a ReadableStream<Uint8Array> representing the body of the request.