How to Preview image before upload with dynamically created input file using Jquery

One thing that jQuery makes really easy is accessing and dynamically modifying the image preview before upload. In popular networking sites such as Facebook and Linkedin, you might have observed the feature called Image Preview. Preview images before the upload are the most required feature for file upload functionality. It helps the user to view chosen file and change the image before upload.

HTML Code

<table class="table">
	<tbody id="appendItem">
		<tr id="RemoveData1">
			<td>
				<img data-val="1" id="previewimage1" class="stockimagepreview" src="img/product_image.gif" style="cursor: pointer;height: 60px;width: 60px;position: relative;z-index: 10;">
				<input data-val="1" class="previewimageUploadFile" id="uploadFile1" name="return[1][product_image][]" style="position: absolute; margin: 0px auto; visibility: hidden;" accept="image/*" type="file">
			</td>
		</tr>

		<tr id="RemoveData2">
			<td>
				<img data-val="2" id="previewimage2" class="stockimagepreview" src="img/product_image.gif" style="cursor: pointer;height: 60px;width: 60px;position: relative;z-index: 10;">
				<input data-val="2" class="previewimageUploadFile" id="uploadFile2" name="return[2][product_image][]" style="position: absolute; margin: 0px auto; visibility: hidden;" accept="image/*" type="file">
			</td>
		</tr>
		<tr id="RemoveData3">
			<td>
				<img data-val="3" id="previewimage3" class="stockimagepreview" src="img/product_image.gif" style="cursor: pointer;height: 60px;width: 60px;position: relative;z-index: 10;">
				<input data-val="3" class="previewimageUploadFile" id="uploadFile3" name="return[3][product_image][]" style="position: absolute; margin: 0px auto; visibility: hidden;" accept="image/*" type="file">
			</td>
		</tr>
	</tbody>
</table>

Jquery / JavaScript Code

<script>
	$('#appendItem').delegate('.stockimagepreview','click',function(){
		var id = $(this).attr('data-val');
		$('#uploadFile'+id).click();

	});

	$('#appendItem').delegate('.previewimageUploadFile','change',function(){
		var id = $(this).attr('data-val');
		readURL(this,id);
	});

	function readURL(input,id) {
		if (input.files && input.files[0]) {
			var reader = new FileReader();
			reader.onload = function (e) {
				$('#previewimage'+id).attr('src', e.target.result);
			}
			reader.readAsDataURL(input.files[0]);
		}
	}
</script>

Leave a Reply

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