Created
January 20, 2020 16:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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