Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to preview a image before uploading it. But it only gets previewed in Microsoft Edge and not in other browsers. How can I make this bootstrap modal browser compatible.

JavaScript
var modal = document.getElementById('imageModal');
       var img = document.getElementById('URI');
       var modalImg = document.getElementById("img01");
       $("#URI").on({
           change: function () {
               $('#imageModal').modal('show')

               modalImg.src = img.value;

       });


HTML
<div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="imageModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="imageModalLabel">Image Preview</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <img class="modal-content-img normal" id="img01"><br />
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" id="caption">Rotate</button>
                            <button type="submit" class="btn btn-primary" id="modalSave">Save changes</button>
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>



What I have tried:

I have implemented the bootstrap modal from getbootstrap.com
Posted
Updated 8-May-17 5:32am

1 solution

What you've got shouldn't work - a page loaded from the internet should not be able to load a file from the user's local file system. The fact that it works in Edge seems like a bug to me.

You can either use URL.createObjectURL[^] or FileReader.readAsDataURL[^] to load a preview of the image. Both will work in all versions of Chrome, Firefox, Opera, Safari and Edge, and will work in IE10 or later.
JavaScript
$("#URI").on({
    change: function () {
        if (this.files && this.files[0]){
            modalImg.src = URL.createObjectURL(this.files[0]);
            $('#imageModal').modal('show');
        }
    }
});
 
Share this answer
 
Comments
Pratik Naik 8-May-17 11:53am    
Thank you!!! That solved it :D
[no name] 8-May-17 12:42pm    
If it helped than I give a 5 ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900