Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Preview selected image (input type=”file”) using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Preview selected image (input type=”file”) using JavaScript</title>
<style>
body {
padding: 1em 0 0 1em;
}
#img-preview {
display: none;
width: 155px;
border: 2px dashed #333;
margin-bottom: 20px;
}
#img-preview img {
width: 100%;
height: auto;
display: block;
}
[type="file"] {
height: 0;
width: 0;
overflow: hidden;
}
[type="file"] + label {
font-family: sans-serif;
background: #f44336;
padding: 10px 30px;
border: 2px solid #f44336;
border-radius: 3px;
color: #fff;
cursor: pointer;
transition: all 0.2s;
}
[type="file"] + label:hover {
background-color: #fff;
color: #f44336;
}
</style>
</head>
<body>
<form>
<div>
<div id="img-preview"></div>
<input
type="file"
accept="image/*"
id="choose-file"
name="choose-file"
/>
<label for="choose-file">Choose File</label>
</div>
</form>
<script>
const chooseFile = document.getElementById("choose-file");
const imgPreview = document.getElementById("img-preview");
chooseFile.addEventListener("change", function () {
getImgData();
});
function getImgData() {
const files = chooseFile.files[0];
if (files) {
const fileReader = new FileReader();
fileReader.readAsDataURL(files);
fileReader.addEventListener("load", function () {
imgPreview.style.display = "block";
imgPreview.innerHTML = '<img src="' + this.result + '" />';
});
}
}
</script>
</body>
</html>
@w3collective

This comment has been minimized.

Copy link
Owner Author

@w3collective w3collective commented Jun 28, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment