Created
September 21, 2017 14:54
-
-
Save CelliesProjects/8ac7038fef4c05e40f91bc70618d6cb4 to your computer and use it in GitHub Desktop.
Simple JS uploader
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
<!-- 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