How to upload file with FormData using Node.JS built-in fetch (not node_fetch)?
1 Answer
To upload file as FormData using NodeJS builtin fetch.
We read the file as Blob then set or append to the FormData object.
And finally we send the FormData object as the body of the fetch request.
To read the file as Blob, we can use the fs.openAsBlob (Node.JS ^19.8) or read file fs.readFile as Buffer and convert it to Blob.
import { openAsBlob } from 'node:fs' // Node.JS ^19.8
import { readFile } from "node:fs/promises"
import { lookup } from "mime-types"
uploadFile("./path/to/file.ext").then(res => res.text()).then(console.info)
async function uploadFile(/** @type {string} */ filePath) {
const file = await openAsBlob(filePath); // or
const file = new Blob([await readFile(filePath)], { type: lookup(filePath) });
const formData = new FormData()
formData.set("file", file, "file_name.ext");
return fetch(`https://example.com/upload`, { method:"POST", body:formData, /* ... */ });
}
3 Comments
BRose
This appears to cause the following error: "Error: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream" any insight on how to resolve that? This error triggers on both formData.append or formData.set
BRose
That didn't seem to matter. Actually it seems to be a known bug the error I was receiving, the absolute only way I could fix it was updating axios to the latest 1.6.8