How to load Fileupload image to <Asp:Image> tag?

Asked

Viewed 463 times

1

My question is how to load the image directly from Fileupload for the tag <asp:Image>

And if it is possible to make these validations by client side and validate type and size via jQuery.

Follows code:

 <div id="img2" style="width: 530px; height: 270px; border: 2px solid rgb(225, 226, 233); box-shadow: rgb(246, 246, 249) 0px 0px 5px inset; background-color: rgba(251, 235, 235, 0.4);">
 <asp:Image ID="imgBanner" runat="server" ImageUrl="~/" Style="border-width: 0px; position: inherit; min-height: 130px; min-width: 130px; top: 20px; bottom: 0; left: 0; right: 0; margin: auto; max-width: 130px; max-height: 130px;" />
 </div>
 <br />
 <br />
 <asp:FileUpload ID="fileUpload"  runat="server"  />

that will result in these components:

inserir a descrição da imagem aqui

1 answer

1


Basically to bring a preview of an image as chosen by input file, using with Filereader is the next:

$("#foto").on('change', function() {
  if (this.files[0].type.indexOf("image") > -1) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#img1').attr('src', e.target.result);
    }
    reader.readAsDataURL(this.files[0]);
  } else {
    $('#img1').attr('src', '');
    alert('Não é uma imagem válida');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="file" name="foto" id="foto" accept="image/*">
<div style="display:table">
  <img id="img1" name="img1" border="0" />
</div>

Observing:

  • along those lines if (this.files[0].type.indexOf("image") > -1) { checks if the item is an image.

and in its code:

<form id="form1" runat="server">
    <div id="img2" style="width: 530px; height: 270px; border: 2px solid rgb(225, 226, 233); box-shadow: rgb(246, 246, 249) 0px 0px 5px inset; background-color: rgba(251, 235, 235, 0.4);">
        <asp:Image ID="imgBanner" runat="server" ImageUrl="~/" Style="border-width: 0px; position: inherit; min-height: 130px; min-width: 130px; top: 20px; bottom: 0; left: 0; right: 0; margin: auto; max-width: 130px; max-height: 130px;" />
    </div>
    <br />
    <br />
    <asp:FileUpload ID="fileUpload" accept="image/*" runat="server" />
</form>
<script>
    $("#<%=fileUpload.ClientID%>").on('change', function () {
        if (this.files[0].type.indexOf("image") > -1) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#<%=imgBanner.ClientID%>').attr('src', e.target.result);
            }
            reader.readAsDataURL(this.files[0]);
        }
        else {                
            $('#<%=imgBanner.ClientID%>').attr('src', '');
            alert('Não é uma imagem válida')
        }
    });
</script>

Examples:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.