-
-
Save cferdinandi/69d794fe3ce668d8c89d551d664a0b19 to your computer and use it in GitHub Desktop.
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
<!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; | |
} | |
#app { | |
margin-bottom: 1em; | |
} | |
img { | |
height: auto; | |
max-width: 100%; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>File Upload</h1> | |
<div id="app"></div> | |
<form id="upload"> | |
<label for="file">File to upload</label> | |
<input type="file" id="file" accept="image/*"> | |
<button>Upload</button> | |
</form> | |
<script> | |
// Get the form and file field | |
let form = document.querySelector('#upload'); | |
let file = document.querySelector('#file'); | |
let app = document.querySelector('#app'); | |
/** | |
* Log the uploaded file to the console | |
* @param {event} Event The file loaded event | |
*/ | |
function logFile (event) { | |
let str = event.target.result; | |
let img = document.createElement('img'); | |
img.src = str; | |
app.append(img); | |
console.log(str); | |
} | |
/** | |
* 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.readAsDataURL(file.files[0]); | |
} | |
// Listen for submit events | |
form.addEventListener('submit', handleSubmit); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can replace base64 URI with Blob URI (shorter code and use less CPU/memory):