Skip to content

Instantly share code, notes, and snippets.

@luoyjx
Created June 18, 2019 08:25
Show Gist options
  • Save luoyjx/a66ea167c0144223962379d23db86d9a to your computer and use it in GitHub Desktop.
Save luoyjx/a66ea167c0144223962379d23db86d9a to your computer and use it in GitHub Desktop.
upload file with node-fetch & form-data
const fetch = require('node-fetch')
const FormData = require('form-data')
const pdfPath = '/path/to/pdfFile'
async function upload () {
const formData = new FormData()
formData.append('name', 'xxx')
formData.append('filename', 'xxxxxxxx.pdf')
formData.append('file', fs.readFileSync(pdfPath), {
filename: 'xxxxxxxx.pdf',
contentType: 'application/pdf'
})
const result = await fetch(
`http://your-api-url/upload`,
{ method: 'post', body: formData }
).then(res => res.json())
return result
}
@mike-pete
Copy link

Thank you so much! I've spent so long trying to do this, I owe you one!

@tjshee39
Copy link

tjshee39 commented Dec 7, 2022

you are angel

@mark-kan
Copy link

Thanks for sharing this!

On fetch I get an error that fetch failed with cause. " cause: TypeError: object2 is not iterable". I am writing the file size in bytes to the console and it is just about the size as the file on disk so the readFileSync seems OK.

Many thanks for any guidance in advance.

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