Skip to content

Instantly share code, notes, and snippets.

@speratus
Created January 20, 2020 16:03
Show Gist options
  • Save speratus/59346196d1b240279852e7899c36d610 to your computer and use it in GitHub Desktop.
Save speratus/59346196d1b240279852e7899c36d610 to your computer and use it in GitHub Desktop.
The correct way to send a file to a server via a backend server via AJAX
document.querySelector("#form").addEventListener(e => {
e.preventDefault()
//Get the file from the file input type
const file = e.target['avatar'].files[0]
const name = e.target['name'].value
const formData = new FormData()
//append the file directly to formData. It's read in automatically
formData.append('avatar', file)
formData.append('name', name)
fetch('http://localhost:3000/', {
method: 'POST',
headers: {
//Note the absence of a "Content-Type" header
'Accept': 'application/json'
},
//We send the formData unmodified in any way.
body: formData
}).then(res => {
//do something with the response
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment