Skip to content

Instantly share code, notes, and snippets.

@wxs77577
Created August 13, 2021 03:10
Show Gist options
  • Save wxs77577/3776fe00b4fb6adfb4f02e809b7f880e to your computer and use it in GitHub Desktop.
Save wxs77577/3776fe00b4fb6adfb4f02e809b7f880e to your computer and use it in GitHub Desktop.
node-fetch使用form-data上传文件
import FormData from 'form-data'
import { readFileSync } from 'fs'
import fetch from 'node-fetch'
const url = 'https://test.com/api'
const name = 'avatar'
const file = readFileSync('./avatar.jpg')
const form = new FormData()
form.append('name', name)
// 不加filename可能会报错
form.append('file', file, { filename: 'avatar.jpg' })
fetch(url, {
method: 'POST',
body: form,
})
.then(res => res.json())
.then(data => console.log(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment