How to Image Preview Before Upload Using JavaScript

Image preview before the upload is a basic and important feature nowadays in profile registration forms. Image preview helps the user to verify the image before uploading. Even more, the user can select another image if needed before submitting a form.

Image preview feature can be implemented through JavaScript, jQuery, or any other JS framework. The image preview feature does not depend on any other back-end languages like PHP, DOT NET, JAVA, Python, etc.

Image Preview Before Upload in JavaScript

The given below HTML code explains the method to preview an image before uploading it to the server.

Example

<html>
<head>
	<title>Image Preview Example Using JavaScript - errorsea.com</title>
</head>
<body>
	<img id="preview_image_container" style="width:150px;height:150px;">
	<br>
	<input type="file" accept="image/*" onchange="image_preview(event)">
	<script type='text/javascript'>
        function image_preview(e){
    	        var reader = new FileReader();
                reader.onload = function(){
			var output = document.getElementById('preview_image_container');
			output.src = reader.result;
		}
		reader.readAsDataURL(e.target.files[0]);
        }
	</script>
</body>
</html>

Explanation

In the above example, we first create an input field of file type and filter it for only images to upload. Also, we create an image element with preview_image_container id to preview the chosen image. After that, we create the image_preview() function and set it to onchange event for the input field. In the image_preview() function, we pass an event of file selection.

When the onchange event triggers, our image_preview() function will be called. In the image_preview() function event will be passed as an argument. That event will hold the image file’s source and will be set to the src attribute of the #preview_image_container image element.

Here, we created a 300X300 px image container for preview. However, we can create our own preview section with custom CSS.

Read Also: How to Compress Image Size Without Losing Quality in PHP

Conclusion

In the above article, we learned about the image preview process via a JavaScript function. I hope now you have a complete understanding of image preview before upload an image file.

Enjoy Coding πŸ™‚

Leave a Reply

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