首页 > 解决方案 > 选择文件后引导文件选择字段未更新

问题描述

我在 Django 模板中使用 Bootstrap v4.5.0(不确定是否相关)。具体来说,我正在使用 Bootsrap 表单组件(根据https://getbootstrap.com/docs/4.5/components/forms/)来显示我的表单元素。

虽然我可以使用表单来选择文件并很好地上传,但表单永远不会更新以显示文件已被选中。这是一个问题,因为我让用户认为我的 Web 应用程序没有理由不接受他们的文件。

我包括了所有需要的 JavaScript,并且我已经在不同的浏览器中进行了测试,所以我不确定问题出在哪里。在这个阶段,我宁愿不使用不同版本的 Bootstap,也不认为这是版本的问题。

我附上了一段演示这个问题的片段:

<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
</head>
<body>
<div class="custom-file">
    <input class="custom-file-input" id="customFile1" name="testfile" type="file" /><label class="custom-file-label" for="customFile1">Upload a file</label>
</div>
</body>
</html>

如果我错过了明显的东西,我将不胜感激任何指示或指出,谢谢。

标签: htmltwitter-bootstrapbootstrap-4

解决方案


您需要使用 javascript 来显示所选文件的名称。

$('#inputFile').on('change', function() {
  //get the file name
  var fileName = $(this)[0].files[0].name;
  //replace the "Choose a file" label
  $(this).next('.file-name').html(fileName);
})
<html lang="en">

<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</head>

<body>
  <div class="input-group mb-3">
    <div class="custom-file">
      <input type="file" class="custom-file-input" id="inputFile" />
      <label class="file-name" for="inputFile">Click Me To Choose File </label>
    </div>

  </div>
  </div>

</body>

</html>


推荐阅读