Sandhya
Sandhya

Reputation: 93

How to preview uploaded image in file upload control before save using asp.net or jquery?

I want to preview image which is uploaded using file upload contorl in asp.net before save.

I tried code using filereader but that is not working in IE9 reader is not supported in ie9.

Upvotes: 3

Views: 17066

Answers (3)

vishpatel73
vishpatel73

Reputation: 317

How to preview uploaded image in file upload control before save using asp.net or jquery?

This will preview multiple files as thumbnail images at a time

Html

<input id="ImageMedias" multiple="multiple" name="ImageMedias" type="file"
accept=".jfif,.jpg,.jpeg,.png,.gif" class="custom-file-input"  value="">                                    
<div id="divImageMediaPreview"></div>

Script

$("#ImageMedias").change(function () {
    if (typeof (FileReader) != "undefined") {
        var dvPreview = $("#divImageMediaPreview");
        dvPreview.html("");            
        $($(this)[0].files).each(function () {
            var file = $(this);                
                var reader = new FileReader();
                reader.onload = function (e) {
                    var img = $("<img />");
                    img.attr("style", "width: 150px; height:100px; padding: 10px");
                    img.attr("src", e.target.result);
                    dvPreview.append(img);
                }
                reader.readAsDataURL(file[0]);                
        });
    } else {
        alert("This browser does not support HTML5 FileReader.");
    }
});

Working Demo on Codepen

Working Demo on jsfiddle

I hope this will help.

Upvotes: 2

Pabli770
Pabli770

Reputation: 131

The example of @Manoj works in IE 11 but no need to call the change function:

function readURL(input) {
    if (input.files && input.files[0]) {
    var reader = new FileReader();

        reader.onload = function (e) {
           $('#image_upload_preview').attr('src', e.target.result);
        }

    reader.readAsDataURL(input.files[0]);
    }
}  

with this code is enough.

Upvotes: 0

Manoj
Manoj

Reputation: 5071

Try this example

Html

<form id="form1" runat="server">
    <input type='file' id="inputFile" />
    <img id="image_upload_preview" src="http://placehold.it/100x100" alt="your image" />
</form>

Script

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#image_upload_preview').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#inputFile").change(function () {
    readURL(this);
});

This will help you.

Working Demo

Upvotes: 4

Related Questions