Image Preview Before Uploading Using JavaScript

In this tutorial i will show you how to Image Display Before Uploading Using JavaScript. You can see demo on click below button and source code also available here.

Demo Download

Step to display image before uploading using JavaScript.

To display image before uploading using JavaScript we need to follow below all steps

  • Create HTML File
  • Create CSS File
  • Generate JavaScript

1: Create HTML File

First of all we create a index.html file and in head section we need to connection with style.css file. Below all codes paste in body section

	<div class="container">
		<form action="" method="post" enctype="multipart/form-data">
			<input type="file" id="image" onchange="loadfile(event)">
			<label for="image">
				Choose a Photo
			</label>
			<input type="submit" value="Upload" class="btn">

		</form>
		<img id="preimage" src="default.png">
	</div>

In above code, we create a form and input file with input submit button and in the last we create a img tag for displaying image before uploading.

2: Create CSS File

Second we create a style.css file and make sure css file connected with index file.

*{
	margin: 0;
	padding: 0;
}
body{
	width: 100%;
	height: 100vh;
	display: flex;
	justify-content: center;
	align-items: center;
}
.container{
	position: relative;
	width: 50%;
	padding: 20px;
	background-color: #c9c9c9;
	border-radius: 10px;
}
#image{
	float: left;
	width: 50%;
}
input[type="file"]{
	display: none;
}
label{
	color: white;
	height: 40px;
	width: 40%;
	border-radius: 20px;
	background: linear-gradient(180deg,#32a852,#03d1ff);
	position: absolute;
	font-size: 18px;
	text-align: center;
	line-height: 40px;
}
.btn{
	float: right;
	width: 50%;
	height: 40px;
	border-radius: 20px;
	background: linear-gradient(180deg,#32a852,#03d1ff);
	background-size: 300%;
	color: #fff;
	cursor: pointer;
	font-size: 18px;
}
#preimage{
	width: 100%;
	margin-top: 10px;
	border-radius: 10px;
}

In above code, we create a style on input [type file], input [type submit] and also style on img tag.

3: Generate JavaScript

Third, we generate a JavaScript code for display image when we select from location before uploading. this below code copy and paste in end of body section.

	<script type="text/javascript">
		function loadfile(event){
			var output = document.getElementById('preimage');
			output.src = URL.createObjectURL(event.target.files[0]);
		};
	</script>

In above code, this code to action for display image.

Conclusion

Today we learnt how to display image before uploading using JavaScript.

If you found this tutorial helpful, share it with your friends and developers group.

Demo Download

I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook and share it.

Facebook Official Page: T-Code Scripts

Leave a Reply

Your email address will not be published. Required fields are marked *