Created
December 16, 2018 21:39
-
-
Save peterekepeter/25953cff88081cde05ef8e82dcaf3563 to your computer and use it in GitHub Desktop.
A short example on how to accept images from filesystem and displaying them using HTML5
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
<style type="text/css"> | |
#dropArea{ | |
min-width:400px; | |
min-height:400px; | |
border:2px dashed #ccc; | |
border-radius:4px; | |
font-family:sans-serif; | |
display:flex; | |
align-items:center; | |
justify-content:center; | |
flex-flow: column nowrap; | |
transition: background 200ms linear; | |
} | |
#dropArea.over{ | |
background:#ccc; | |
transition: background 200ms linear; | |
} | |
#infoArea{ | |
text-align:center; | |
} | |
</style> | |
<div id="dropArea"> | |
<div id="infoArea"> | |
<h2 id="heading">Drop your image here!</h2> | |
<p id="infoParagraph">It can be any image from your filesystem!</p> | |
</div> | |
<img id="previewImage"></img> | |
</div> | |
<script type="text/javascript"> | |
function main(){ | |
dropArea.ondrop = receiveDroppedItem; | |
dropArea.ondragover = allowDroppingItems; | |
dropArea.ondragleave = resetDropStyles; | |
} | |
function receiveDroppedItem(event){ | |
event.preventDefault(); | |
console.log(event); | |
var file = event.dataTransfer.files[0]; | |
console.log(file); | |
heading.textContent = file.name; | |
infoParagraph.textContent = "Last Modified: "+ new Date(file.lastModified).toLocaleString(); | |
previewImage.src = file; | |
var reader = new FileReader(); | |
reader.onload = function(event){ | |
previewImage.src = event.target.result; | |
resetDropStyles(); | |
}; | |
reader.readAsDataURL(file); | |
} | |
function allowDroppingItems(event){ | |
event.preventDefault(); | |
dropArea.classList.toggle("over", true); | |
} | |
function resetDropStyles(){ | |
dropArea.classList.toggle("over", false); | |
} | |
document.addEventListener("DOMContentLoaded",main); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment