Saturday, January 28, 2017

Part 32 - Preview Image before upload using JQuery in Asp.net mvc




#Expected Output 



 #View Page  (Index.cshtml)


@model MVCTutorial.Models.ModelC
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

<div class="panel panel-body" style="min-height:256px">
        
    <div class="col-md-9">

        <div class="col-md-4">
            <div class="btn btn-primary">
                <input type="file" id="imageBrowes" />
            </div>
            <hr />

            <div id="imgPreview" class="thumbnail" style="display:none">
                <img class="img-responsive" id="targetImg" />
                <div class="caption">
                    <a href="#" onclick="ClearPreview()"><i class="glyphicon glyphicon-trash"></i></a>
                    <span id="description"></span>
                </div>
            </div>

        </div>

    </div>

</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>

    $(document).ready(function () {

        $("#imageBrowes").change(function () {           

            var File = this.files;

            if (File && File[0]) {
                ReadImage(File[0]);
            }

        })


    })


    var ReadImage = function (file) {

        var reader = new FileReader;
        var image = new Image;

        reader.readAsDataURL(file);
        reader.onload = function (_file) {

            image.src = _file.target.result;
            image.onload = function () {

                var height = this.height;
                var width = this.width;
                var type = file.type;
                var size = ~~(file.size / 1024) + "KB";

                $("#targetImg").attr('src', _file.target.result);
                $("#description").text("Size:" + size + ", " + height + "X " + width + ", " + type + "");
                $("#imgPreview").show();

            }

        }

    }

    var ClearPreview = function () {
        $("#imageBrowes").val('');
        $("#description").text('');
        $("#imgPreview").hide();

    }

</script>


   

All Code Factory

3 comments:

Ashish said...

Our next video - how to upload image to server will be published soon..

Ashish said...

Google plus comment section has been removed. Now all can get reply to corresponding message..

mcuambe said...

Hi everyone,
its really helpful

many thanks