Skip to content

Instantly share code, notes, and snippets.

@phannam1412
Last active October 5, 2016 11:05
Show Gist options
  • Save phannam1412/f8aa3279409a9b2c2503b1fd92aafb99 to your computer and use it in GitHub Desktop.
Save phannam1412/f8aa3279409a9b2c2503b1fd92aafb99 to your computer and use it in GitHub Desktop.
Ajax file upload with javascript
<html>
<head></head>
<body>
<input type="file" id="file">
<script type="text/javascript">
var fileSelect = document.getElementById('file');
fileSelect.onchange = function (e) {
// 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];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('files[]', file, file.name);
// Set up the request.
var xhr = new XMLHttpRequest();
// Open the connection.
xhr.open('POST', 'index.php', 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>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment