Preview picture before upload with jquery

This code is to let the user view the selected picture on the page before uploading it. Hiding the file input and using javascript to access it is helpful for design purposes. If you use your file input type on the page, then you can ignore the first 3 lines of code.


    <!--HTML-->
    <img id="preview" title="" alt="" />
    <button class="change-profile-pic">Change Picture</button>
    <input id="profile-pic" style="display: none;" type="file" />
 
    //jquery
    $(".change-profile-pic").on("click", function () {
            $("#profile-pic").click();
    });
    $("#profile-pic").change(function () {
            readURL(this);
    });
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#preview').attr('src', e.target.result);
            };
            reader.readAsDataURL(input.files[0]);
        }
    }

Be the first to comment “Preview picture before upload with jquery”

This site uses Akismet to reduce spam. Learn how your comment data is processed.