UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Fileupload control with image preview Asp.net

Demo and code for how to preview image before upload in Asp.net using jQuery

by Athil


Posted on 04 Apr 2020 Category: Asp.Net Views: 137


Here Iam going to show how to preview image befroe upload in asp.net using jQuery

for this we need to link jQuery library in our page.

DEMO

DWONLOAD DEMO

  <script src="js/jquery.min.js"></script>

Add one file upload and image control.

<asp:FileUpload ID="ImgUpload" accept="image/x-png,image/gif,image/jpeg"  onchange ="readURL(this);" runat="server" /> <br/>
<asp:Image ID="imgPrev" runat="server" ImageUrl ="https://examples.unclecoder.com/images/no-image-found-360x250.png"   style="width:200px;height:auto;" />

In the above code I give file upload control with id ImgUpload  that will accept png/gif/jpeg files. If need more types we can add in accept attribute.

And one image control aslo added with id imgPrev  for preview images and the with I mentioned 200px in style and heht will be automatically adjust accroding to the size of image.

 

Add the bellow jQuery script to get the preview.

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

 



Leave a Comment: