Created
September 24, 2019 10:15
-
-
Save pinkhominid/e6f53706e0dd8cf34f2bd94c3aa357c5 to your computer and use it in GitHub Desktop.
Upload a file with node-fetch and form-data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); |
Really helpful, thanks!
Very helpful, thanks a lot!!!
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 :-)
to clarify for TS devs that land here:
- add form-data
yarn add --exact form-data
- restart ts lang server
Command Palette -> Restart TS Server
- deal with correct types
Really helpful, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.