Skip to content

Instantly share code, notes, and snippets.

@justsml
Created November 16, 2018 23:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justsml/301f22aa37df565ba3051bd5f95b4df1 to your computer and use it in GitHub Desktop.
Save justsml/301f22aa37df565ba3051bd5f95b4df1 to your computer and use it in GitHub Desktop.
postFile('http://example.com/api/v1/users', 'input[type="file"].avatar')
.then(data => console.log(data))
function postFile(url, fileSelector) {
const formData = new FormData()
const fileField = document.querySelector(fileSelector)
formData.append('username', 'abc123')
formData.append('avatar', fileField.files[0])
return fetch(url, {
method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
body: formData // Coordinate the body type with 'Content-Type'
})
.then(response => response.json())
.catch(error => console.error(error))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment