Last active
August 29, 2015 14:27
-
-
Save steinbring/158332567682199dab73 to your computer and use it in GitHub Desktop.
This shows you how to take the contents of a selected image file and display it on change within the page.
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></title> | |
</head> | |
<body> | |
<!-- We are going to display it in an <img> tag, so we will only accept image files --> | |
<input type='file' accept='images/*' onchange='openFile(event);'> | |
<div id="TheImageContents"> | |
</div> | |
<script type="text/javascript"> | |
// This grabs the file contents when the file changes | |
var openFile = function(event) { | |
var input = event.target; | |
// Instantiate FileReader | |
var reader = new FileReader(); | |
reader.onload = function(){ | |
TheFileContents = reader.result; | |
// Update the output to include the <img> tag with the data URL as the source | |
document.getElementById("TheImageContents").innerHTML = '<h2>The image that you selected</h2><p><img width="200" src="'+TheFileContents+'" /></p>'; | |
}; | |
// Produce a data URL (base64 encoded string of the data in the file) | |
// We are retrieving the first file from the FileList object | |
reader.readAsDataURL(input.files[0]); | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment