Preview image in base64 format using jQuery on change input file

Updated at 05-Jul-2021, By samar

Preview image in base64 format using jQuery on change input file

Through the use of the programming language, we will work together to solve the "Preview image in base64 format using jQuery on change input file" puzzle in this lesson.

You can preview images in Base64 encoded format using jQuery on the change input file.
  • Display image in base64 format on change input file

    <!--  Preview image in base64 formats -->
    <input type="file" name="image" id="image"/>
    <div class="previewWrapper" style="height:200px; width:300px;">
        <img id="previewImage" style="height:100%; width:100%;">
    </div>
    
    <!-- script -->
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
        $(document).ready(function(){
            $("body").on("change", "#image", function(e){
                var file = e.target.files[0];
                var mediabase64data; 
                getBase64(file).then(
                    mediabase64data => $('#previewImage').attr('src', mediabase64data)
                );
            });
        })
        
        function getBase64(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            });
        }
    </script>
    

Back to code snippet queries related jquery