How to Image Preview before upload using Jquery

In popular networking sites such as Facebook and Linkedin, you might have observed the feature called Image Preview. Preview image before upload is a most required feature for file upload functionality. It helps the user to view chosen file and change the image before upload.

HTML Code

<div class="form-group">
	<label class="col-md-2 control-label">Product Image<span class="text-danger">*</span></label>
	<div class="col-md-7">
		<img id="previewimage" onclick="$('#uploadFile').click();" src="<?php echo base_url(); ?>images/product_image.gif" style="cursor: pointer;height: 210px;width: 210px;position: relative;z-index: 10;"/>
		<input type="file" id="uploadFile" name="product_image" style="position: absolute; margin: 0px auto; visibility: hidden;" accept="image/*" />
		<div style="margin-top: 0px; color: red;"><?= form_error('product_image'); ?></div>
	</div>
</div>

Jquery / JavaScript Code

function previewImage(input) {
	if (input.files && input.files[0]) {
				var reader = new FileReader();

				reader.onload = function (e) {
						$('#previewimage').attr('src', e.target.result);
				}
				reader.readAsDataURL(input.files[0]);
	}
}
$("#uploadFile").change(function(){
	previewImage(this);
});

Leave a Reply

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