Skip to content

Instantly share code, notes, and snippets.

@mul14
Last active October 13, 2020 06:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mul14/6b5601f708bbd672d0a22d750b25c6fb to your computer and use it in GitHub Desktop.
Save mul14/6b5601f708bbd672d0a22d750b25c6fb to your computer and use it in GitHub Desktop.
JavaScript Upload FormData
<form id="form">
  <input type="name" name="full_name" />
  <input type="file" name="image" />
  <button type="submit">Submit</button>    
</form>
// Fetch

const form = new FormData(document.querySelector('#form'))

fetch('/', {
  method: 'POST',
  body: form,
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})
// Axios

const form = new FormData(document.querySelector('#form'))

axios.post('/', form)

// The "Content-Type: multipart/form-data" header's will automatically injected by axios.
// Empty FormData

const form = new FormData()
form.append('full_name', 'Mulia Nasution')
form.append('image', document.querySelector('#form input[name="image"]'))

axios.post('/', form)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment