Formatting File Upload Input with Bootstrap
If you’re using file upload forms in your Bootstrap themed website and would like to format the button and the field nicely, take a peek at this article by Cory LaViska. He nails it.
A small example which produces an input-group like this (“Fil” means file in Swedish):
<div class="editor-label"> <label>Fil</label> <div class="input-group"> <span class="input-group-btn"> <span class=" btn btn-default btn-file"> välj fil... <input type="file" name="data" id="data"> </span> </span> <input type="text" id="valdfil" class="form-control" readonly /> </div> </div>
<script type="text/javascript"> $(document).ready(function () { $(document).on('change', '.btn-file :file', function () { var input = $(this), numFiles = input.get(0).files ? input.get(0).files.length : 1, label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); input.trigger('fileselect', [numFiles, label]); }); $('.btn-file :file').on('fileselect', function (event, numFiles, label) { console.log(numFiles); console.log(label); $("#valdfil").val(label); }); }); </script>
You must also add these CSS lines:
.btn-file {
position: relative;
overflow: hidden;
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
font-size: 100px;
text-align: right;
filter: alpha(opacity=0);
opacity: 0;
outline: none;
background: white;
cursor: inherit;
display: block;
}