javascriptc#jqueryasp.netimage-uploading

Display image after selecting file


I am trying to display the selected image in file input via JavaScript. Here is the code I used shown below:

<label id="lblFileUploadProfile">
<asp:FileUpload runat="server" ID="ImageProfileUpload"   />
<asp:Image runat="server" ID="ImgProfilePic" ImageUrl="img/user-5.png"  /> 

I use this file input to upload image but have no idea how to display selected image when selecting image? how do i display it just when the upload is done useing JS ?


Solution

  • Try this approach:

    <img id="blah" class="photo" ImageUrl="img/user-5.png" />
    <label for="imgInp" class="custom-file-upload">
        <i class="fa fa-cloud-upload"></i>Add Image
    </label>
    <input type='file' id="imgInp" name="image" />
    
    
    <script>
    //Preview & Update an image before it is uploaded
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
    
                reader.onload = function (e) {
                    $('#blah').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    
        $("#imgInp").change(function () {
            readURL(this);
        });
    </script>
    
    
    <style type="text/css">
    input[type="file"] {
         display: none;
    }
    
    .custom-file-upload {
        border: 1px solid rgb(197, 197, 197);
        border-radius: 4px 4px 4px 4px;
    
        display: inline-block;
        padding: 6px 12px;
        cursor: pointer;
        float: right;
        width: 5.25em;
        margin-left:200px;
    }
    
    .photo{
        width: 7em; 
        height: 9em; 
        border: 1px solid rgb(197, 197, 197); 
        border-radius: 4px 4px 4px 4px; 
        float:right;
    }
    </style>