Skip to content

Instantly share code, notes, and snippets.

@vigosan
Forked from pinkhominid/index.js
Created August 9, 2022 12:31
Show Gist options
  • Save vigosan/c663299ff6da094e7b2e53516be8b7ca to your computer and use it in GitHub Desktop.
Save vigosan/c663299ff6da094e7b2e53516be8b7ca 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;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment