How to load Image from FileUpload to asp: Image tag?

1

My question is how to load the direct image from FileUpload to the tag <asp:Image>

And if it's possible to do these validations on the client side and do the type and size validations via jQuery.

Follow the code below:

 <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:

    
asked by anonymous 20.02.2018 / 20:08

1 answer

1

Basically to bring a preview of an image as you choose from 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><inputtype="file" name="foto" id="foto" accept="image/*">
<div style="display:table">
  <img id="img1" name="img1" border="0" />
</div>

Note:

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

and in your 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:

20.02.2018 / 20:38