基本
<form action="#" method="POST" enctype="multipart/form-data"> <input type="file" name="file"><br><br> <input type="submit" value="upload"> </form>
bootstrap
<form action="#" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="inputFile">File input</label> <div class="custom-file"> <input type="file" class="custom-file-input" id="inputFile"> <label class="custom-file-label" for="inputFile" data-browse="参照">ファイル選択</label> </div> </div> <br> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script> <script> bsCustomFileInput.init(); </script>
画像変更
<form action="#" method="POST" enctype="multipart/form-data"> <img src="https://placehold.jp/200x150.png" class="img-icon"> <div class="preview"></div><br> <div class="form-group"> <label for="inputFile">File input</label> <div class="custom-file"> <input type="file" class="custom-file-input" id="inputFile" name="file1"> <label class="custom-file-label" for="inputFile" data-browse="参照">ファイル選択</label> </div> </div> <br> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script> bsCustomFileInput.init(); $(function(){ $('form').on('change', 'input[name="file1"]', function(e) { var file = e.target.files[0], reader = new FileReader(), $preview = $(".preview"); t = this; if(file.type.indexOf("image") < 0){ return false; } document.getElementsByClassName("img-icon")[0].style.display = "none"; reader.onload = (function(file) { return function(e) { $preview.empty(); $preview.append($('<img>').attr({ src: e.target.result, width: "250px", height: "200px", class: "preview", title: file.name })); }; })(file); reader.readAsDataURL(file); }); }); </script>
object-fit: containにしておきます。
OK^^