mul14
11/21/2018 - 12:05 PM

JavaScript Upload FormData

JavaScript Upload FormData

<form id="form">
    <input type="name" name="full_name" />
    <input type="file" name="image" />
  <button type="submit">Submit</button>    
</form>
// Fetch

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, {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})
// Empty FormData

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

axios.post('/', form, {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})