Skip to content

Instantly share code, notes, and snippets.

@pinkhominid
Created September 24, 2019 10:15
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pinkhominid/e6f53706e0dd8cf34f2bd94c3aa357c5 to your computer and use it in GitHub Desktop.
Save pinkhominid/e6f53706e0dd8cf34f2bd94c3aa357c5 to your computer and use it in GitHub Desktop.
Upload a file with node-fetch and form-data
const fs = require('fs');
const fetch = require('node-fetch');
const FormData = require('form-data');
const filePath = `path/to/file.ext`;
const form = new FormData();
const stats = fs.statSync(filePath);
const fileSizeInBytes = stats.size;
const fileStream = fs.createReadStream(filePath);
form.append('field-name', fileStream, { knownLength: fileSizeInBytes });
const options = {
method: 'POST',
credentials: 'include',
body: form
};
fetch(apiUrl, { ...options })
.then(res => {
if (res.ok) return res;
throw res;
});
@Abadii
Copy link

Abadii commented Dec 31, 2020

Thnx! Helped me a lot

@Kyllingene
Copy link

Really helpful, thanks!

@devnoot
Copy link

devnoot commented Apr 2, 2021

Helped me out, thanks! If anyone runs into issues with Typescript, it may be that you are not importing form-data, and it is grabbing the type definitions for the browser FormData, instead of nodejs's.

@Cecil0o0
Copy link

Really helpful, thanks!

@vvizzard
Copy link

vvizzard commented Mar 6, 2022

Very helpful, thanks a lot!!!

@cahya-wirawan
Copy link

cahya-wirawan commented Oct 3, 2022

Helped me out, thanks! If anyone runs into issues with Typescript, it may be that you are not importing form-data, and it is grabbing the type definitions for the browser FormData, instead of nodejs's.

Thanks @devnoot , I had exactly this issue :-)

@hweeks
Copy link

hweeks commented Nov 29, 2022

to clarify for TS devs that land here:

  1. add form-data
    • yarn add --exact form-data
  2. restart ts lang server
    • Command Palette -> Restart TS Server
  3. deal with correct types

@YeDaxia
Copy link

YeDaxia commented Dec 21, 2022

Really helpful, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment