Skip to main content

Preview image in BLOB URL format on choose file in jQuery

You can display an image in BLOB URL format on the change input file in jQuery. These Code snippets help you to convert an input type file (image) to BLOB URL format (blob:http://project.test/1aacb900-a826-476b-b2de-2d51110ddc94) and display it as an image in an HTML document.

  • Preview image in BLOB URL format on change input type file

    <h1> Image Preview on choose file  in BLOB url format </h1>
    <input type="file" name="image" id="image"/>
    <div id="previewWrapper" style="height:200px; width:300px;">
        <img id="previewImage" style="height:100%; width:100%;">
    </div>
    
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
        $(document).ready(function(){
            $("body").on("change", "#image", function(e){
                previewImage(this, 'previewImage');
            });
        })
        
        function previewImage(input, targetDivToShow) {
            var files = input.files;
            var url;
            var done = function (url) {
                $('#'+targetDivToShow).attr('src', url);
            };
            
            if (input.files && input.files[0]) {
                file = input.files[0];
                if (URL) {
                    done(URL.createObjectURL(file));
                } else if (FileReader) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        done(reader.result);
                    }
                    reader.readAsDataURL(file);
                }
            }
        }
    </script>
    
  • Back to code snippet queries related jquery