showing uploaded image within div

  • When I upload the image can you tell me how to show image within the red box
  • Providing code below

http://codepen.io/anon/pen/ZWXmpd

<div class="upload-image">
    <div class="upload-image-preview"></div>
    <input type="file" name="file" value="Upload Image" />
</div>

Answers 1

  • You can do this using following jQuery.

    $("input[name=file]").change(function () {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
    
            reader.onload = function (e) {
                var img = $('<img>').attr('src', e.target.result);
                $('.upload-image-preview').html(img);
            };
    
            reader.readAsDataURL(this.files[0]);
        }
    });
    

    Use following CSS to keep image size same as the preview div.

    .upload-image-preview img{
        width: 100%;
        height:  100%;
    }
    

    DEMO


Related Articles