Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save markrahimi/c53a4fc27a4443fd74d8ed0a80794851 to your computer and use it in GitHub Desktop.
Save markrahimi/c53a4fc27a4443fd74d8ed0a80794851 to your computer and use it in GitHub Desktop.
Browse button in bootstrap 4 with select image preview
<div class="ml-2 col-sm-6">
<div id="msg"></div>
<form method="post" id="image-form">
<input type="file" name="img[]" class="file" accept="image/*">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file">
<div class="input-group-append">
<button type="button" class="browse btn btn-primary">Browse...</button>
</div>
</div>
</form>
</div>
<div class="ml-2 col-sm-6">
<img src="https://placehold.it/80x80" id="preview" class="img-thumbnail">
</div>
$(document).on("click", ".browse", function() {
var file = $(this).parents().find(".file");
file.trigger("click");
});
$('input[type="file"]').change(function(e) {
var fileName = e.target.files[0].name;
$("#file").val(fileName);
var reader = new FileReader();
reader.onload = function(e) {
// get loaded data and render thumbnail.
document.getElementById("preview").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
.file {
visibility: hidden;
position: absolute;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment