Adds

Thursday, 6 March 2014

Display Image in asp.net C# web form after click file upload using Javascript

Javascript:

<script type="text/javascript">
    function previewFile() {
        var preview = document.querySelector('#<%=Avatar.ClientID %>');
        var file = document.querySelector('#<%=avatarUpload.ClientID %>').files[0];
        var reader = new FileReader();

        reader.onloadend = function () {
            preview.src = reader.result;
        }

        if (file) {
            reader.readAsDataURL(file);
        } else {
            preview.src = "";
        }
    }
    </script>

 .aspx page code:

    <p>
        <asp:Image ID="Avatar" runat="server" Height="225px" ImageUrl="~/Images/NoUser.jpg" Width="225px" />
    </p>
    <p>
        <input ID="avatarUpload" type="file" name="file" onchange="previewFile()"  runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload"/>   
    </p>