Skip to content

Instantly share code, notes, and snippets.

@CelliesProjects
Created September 21, 2017 14:54
Show Gist options
  • Save CelliesProjects/8ac7038fef4c05e40f91bc70618d6cb4 to your computer and use it in GitHub Desktop.
Save CelliesProjects/8ac7038fef4c05e40f91bc70618d6cb4 to your computer and use it in GitHub Desktop.
Simple JS uploader
<!-- http://blog.teamtreehouse.com/uploading-files-ajax -->
<form id="file-form" action="api/upload" method="POST">
<input type="file" id="file-select" name="photos[]" multiple/>
<button type="submit" id="upload-button">Upload</button>
</form>
<script>
var form = document.getElementById('file-form');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
form.onsubmit = function(event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
// The rest of the code will go here...
// Get the selected files from the input.
var files = fileSelect.files;
// Create a new FormData object.
var formData = new FormData();
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
/*
console.log("entering mime chck");
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
*/
// Add the file to the request.
formData.append('photos[]', file, file.name );
formData.append(name, file, file.name);
// Set up the request.
var xhr = new XMLHttpRequest();
// Open the connection.
xhr.open('POST', 'api/upload', true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
uploadButton.innerHTML = 'Upload';
} else {
alert('An error occurred!');
}
};
// Send the Data.
xhr.send(formData);
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment