7

How to upload file with FormData using Node.JS built-in fetch (not node_fetch)?

1 Answer 1

14

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, /* ... */ });
}

Sign up to request clarification or add additional context in comments.

3 Comments

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
Make sure your FormData is from NodeJS.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.