How to select and upload image file using JQuery ajax
A Pen by Zaid Bin Khalid on CodePen.
<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" /> |