【问题标题】:Bootstrap multiple file selection - show only first file引导多个文件选择 - 仅显示第一个文件
【发布时间】:2020-07-26 15:24:53
【问题描述】:

我使用引导自定义文件输入 - 这是非常好的事情,但我不知道如何显示我所有上传的文件。每次当我尝试选择多个文件并上传它们时 - 都正确传递,除了这个 - 在输入表单中只显示第一个文件。

代码

<form>
  <div class="custom-file">
    <input type="file" class="custom-file-input" id="customFile">
    <label class="custom-file-label" for="customFile">Choose file</label>
  </div>
</form>

<script>
// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function() {
  var fileName = $(this).val().split("\\").pop();
  $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
</script>

我可以在表单代码中添加multiple = "" - 但是我应该添加什么才能使所有要上传的文件出现在输入行中?

【问题讨论】:

标签: javascript html twitter-bootstrap


【解决方案1】:

这是你想看到的吗?我不确定 value 属性在 file-input 上的行为如何,但您肯定可以在输入的 files 属性中看到每个文件,所以我只是从中创建了一个字符串。

// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function() {
  var files = Array.from(this.files)
  var fileName = files.map(f =>{return f.name}).join(", ")
  $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<form>
  <div class="custom-file">
    <input type="file" class="custom-file-input" id="customFile" multiple>
    <label class="custom-file-label" for="customFile">Choose file</label>
  </div>
</form>

【讨论】:

    【解决方案2】:

    在 jQuery 中,您可以通过输入元素的.prop('files') 访问 FileObject,请参阅下面的此测试

    $("input").on("input", function() {
      var names = $(this).prop('files');
      for( var i = 0; i < names.length ; i++){
        console.log( names[ i ].name )
      }
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    <form>
      <div class="custom-file">
        <input type="file" class="custom-file-input" id="customFile" multiple="multiple">
        <label class="custom-file-label" for="customFile">Choose file</label>
      </div>
    </form>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2016-10-19
      • 2012-08-17
      • 1970-01-01
      相关资源
      最近更新 更多