Search code examples
asp.netrazor

razor: pick a local image


I am trying to create a form where the user can pick an image with the image being displayed without the page having to be submitted.

I did this in the frontend so far:

<tr>
    <td>
        <input type="file" name="updoc" id="upoc" class="form-control" />
    </td>
    <td>
        <img id="Userpic" class="pull-right" style="margin-bottom: 7px" width="180" height="100" src="@ViewBag.pic" />
    </td>
</tr>

That does display an input field to pick images. Once an image is picked, it displayes the filename on the page but nothing else.

I dont know how to display the image that I just retrieved. Any help would be greatly appreciated!


Solution

  • You can use the jquery FileReader for that.

    <script>
        $('#upoc').bind('change', function () {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#Userpic').attr('src', e.target.result);
            };
    
            reader.readAsDataURL($(this)[0].files[0]);
        });
    </script>