-
-
Save xnohat/ad606f41c18438734ccfeaa38fbfa4b1 to your computer and use it in GitHub Desktop.
Upload a file with node-fetch and form-data
This file contains hidden or 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; | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
npm install [email protected]
for require instead import