I have a file input
that allows the user to upload an image. After selecting an image, a modal opens with the uploaded image displayed inside.
You can view a demo of this functionality in action on this Fiddle Example:
Here is the corresponding code snippet:
$("#input").on("change", function(e) {
var _URL = window.URL || window.webkitURL,
file = this.files[0],
image = new Image();
$('#image').attr('src', _URL.createObjectURL(file));
$(image).ready(function($) {
$('#modal').modal('show');
});
window.URL.revokeObjectURL(image.src);
});
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.bundle.min.js"></script>
<!-- Input for uploading images -->
<input type="file" id="input" name="image">
<!-- Modal for displaying uploaded image -->
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Image Upload</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div> <!-- .modal-header -->
<div class="modal-body">
<div class="container">
<!-- Uploaded Image -->
<img id="image" src="" alt="Picture">
</div> <!-- .container -->
</div> <!-- .modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div> <!-- .modal-footer -->
</div> <!-- .modal-content -->
</div> <!-- .modal-dialog -->
</div> <!-- .modal -->
However, if I close the modal and try to upload the same image again, it does not open as expected because I am using the 'change' event listener.
I attempted to use the 'click' event instead:
$("#input").on("click", function(e) {});
Unfortunately, this resulted in errors and the modal not being shown:
Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the provided signature.
My next step will be to check the dimensions and size of the uploaded image.
So how do I modify my code to ensure that if I choose the same image again, it will still display properly in the modal?