Site icon SmartTutorials.net

Instant Image Preview Before Upload Using jQuery

In this tutorial we are going to see how to implement image preview before upload or before submitting form using jquery.

So what we are doing here is once user select his image or images using input file field, then using change event of jQuery we get all the selected images. Then read the all selected images using FileReader and assign all the read images to image tag.

 

Instant Image Preview Before Upload Using jQuery

Design HTML Image Preview Form :

Please design your image preview form using html5 and css3. or else use below html5 script to desing your jquery image preview form.

 

<form role="form" method="post" enctype="multipart/form-data">
	<div class="form-group">
		<label for="file">Choose your Image: </label>
		<input type="file"  class="coverimage" id="file" name="file[]" multiple>
	</div>
	<div id="image_container">
	</div>	
</form>

 

 

Image Preview jQuery Script:

Below jQuery script get all selected images once user selects his images using change event of jQuery. Then read all selected images using FileReader and assign all read images to image field.

$(document).ready(function($){
	images = new Array();
	$(document).on('change','.coverimage',function(){
		 files = this.files;
		 $.each( files, function(){
			 file = $(this)[0];
			 if (!!file.type.match(/image.*/)) {
	        	 var reader = new FileReader();
	             reader.readAsDataURL(file);
	             reader.onloadend = function(e) {
	            	img_src = e.target.result; 
	            	html = "<img class='img-thumbnail' style='width:300px;margin:20px;' src='"+img_src+"'>";
	            	$('#image_container').append( html );
	             };
        	 } 
		});
	});
});

.

Exit mobile version