Last active
November 27, 2016 16:45
-
-
Save BorisKotlyarov/b5cc21c79918f6899c8f96447d336061 to your computer and use it in GitHub Desktop.
Preview uploaded image and converting it into a base64 string
This file contains hidden or 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 lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Image to Base64</title> | |
</head> | |
<body> | |
<style> | |
body { | |
text-align: center; | |
} | |
.file-input{ | |
padding: 10px; | |
margin: 10px; | |
} | |
.view-box { | |
height: 400px; | |
} | |
.view-image { | |
width: 49%; | |
float: left; | |
} | |
.view-image img{ | |
max-width: 100%; | |
} | |
.image-data { | |
float: right; | |
width: 49%; | |
height: 100%; | |
} | |
.image-data:after { | |
display: block; | |
clear: both; | |
} | |
</style> | |
<div class="file-input"> | |
<input type="file" accept="image/*" data-selector="change-image" /> | |
</div> | |
<div class="view-box"> | |
<div class="view-image" data-selector="view-image">Chose image</div> | |
<textarea class="image-data" data-selector="image-data"></textarea> | |
</div> | |
<script> | |
const changeImage = document.querySelector('[data-selector="change-image"]'); | |
const viewImage = document.querySelector('[data-selector="view-image"]'); | |
const imageData = document.querySelector('[data-selector="image-data"]'); | |
changeImage.addEventListener('change', onchangeFile); | |
function onchangeFile(ev){ | |
viewImage.innerHTML = ''; | |
viewImage.innerHTML = 'loading...'; | |
let img = new Image(); | |
let reader = new FileReader(); | |
reader.onload = function (e) { | |
img.src = e.target.result; | |
imageData.value = e.target.result; | |
} | |
img.onload = function () { | |
viewImage.innerHTML = ''; | |
viewImage.appendChild(img); | |
}; | |
reader.readAsDataURL(changeImage.files[0]); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment