Skip to content

Instantly share code, notes, and snippets.

@justsml
Created November 16, 2018 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justsml/d17f50c36a5ddb70f584c0aa6de94237 to your computer and use it in GitHub Desktop.
Save justsml/d17f50c36a5ddb70f584c0aa6de94237 to your computer and use it in GitHub Desktop.
postFile('http://example.com/api/v1/users', 'input[type="file"].files')
.then(data => console.log(data))
function postFile(url, fileSelector) {
const formData = new FormData()
const fileFields = document.querySelectorAll(fileSelector)
// Add all files to formData
Array.prototype.forEach.call(fileFields.files, f => formData.append('files', f))
// Alternatively for PHPeeps, use `files[]` for the name to support arrays
// Array.prototype.forEach.call(fileFields.files, f => formData.append('files[]', f))
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