Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Last active July 21, 2023 15:30
Show Gist options
  • Save cferdinandi/ed2d0b1cf04e6b860e8a70ed21f6b33a to your computer and use it in GitHub Desktop.
Save cferdinandi/ed2d0b1cf04e6b860e8a70ed21f6b33a to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
<style type="text/css">
body {
margin: 0 auto;
max-width: 40em;
width: 88%;
}
label,
input {
display: block;
width: 100%;
}
input {
margin-bottom: 1em;
}
</style>
</head>
<body>
<h1>File Upload</h1>
<form id="upload">
<label for="file">File to upload</label>
<input type="file" id="file" accept=".json">
<button>Upload</button>
</form>
<script>
// Get the form and file field
let form = document.querySelector('#upload');
let file = document.querySelector('#file');
/**
* Log the uploaded file to the console
* @param {event} Event The file loaded event
*/
function logFile (event) {
let str = event.target.result;
let json = JSON.parse(str);
console.log('string', str);
console.log('json', json);
}
/**
* Handle submit events
* @param {Event} event The event object
*/
function handleSubmit (event) {
// Stop the form from reloading the page
event.preventDefault();
// If there's no file, do nothing
if (!file.value.length) return;
// Create a new FileReader() object
let reader = new FileReader();
// Setup the callback event to run when the file is read
reader.onload = logFile;
// Read the file
reader.readAsText(file.files[0]);
}
// Listen for submit events
form.addEventListener('submit', handleSubmit);
</script>
</body>
</html>
{
"name": "Merlin",
"age": "old AF",
"spells": ["Dancing brooms", "Transform into animal"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment