【问题标题】:Bootstrap 4 File InputBootstrap 4 文件输入
【发布时间】:2017-09-01 04:39:09
【问题描述】:

我正在努力使用 bootstrap 4 文件浏览器。如果我使用自定义文件控制,我会一直看到选择文件值。 https://v4-alpha.getbootstrap.com/components/forms/#file-browser

我想在选择文件后更改选择文件的值。这个值实际上隐藏在 css .custom-file-control:lang(en)::after 中,我不知道如何在 javascript 中访问和更改它。我可以像这样获取所选文件的值:

document.getElementById("exampleInputFile").value.split("\\").pop();

我不需要改变

.custom-file-control:lang(en)::after {
    content: "Choose file...";
}

不知何故

链接:http://codepen.io/Matoo125/pen/LWobNp

【问题讨论】:

  • 这个问题之前已经回答过:stackoverflow.com/questions/37713126/…
  • 不是真的,我问如何更改 css 属性内容,因为那是 Bootstrap 4 以这种方法呈现文本的地方。我没有看到价值
  • 但我想根据输入值动态访问它。我怎样才能用 css 做到这一点?
  • 首先,您是否设法使用 CSS 更改占位符/按钮的值?取值的过程已经在其他问题中回答了
  • 我可以使用 JS 选择值,但在引导程序 4 中,此“占位符”值位于 ::after { content : "..." } 中,我需要更改它以查看更改跨度>

标签: javascript jquery css twitter-bootstrap bootstrap-4


【解决方案1】:

2021 年更新

引导程序 5

自定义文件输入不再存在,因此要更改 Choose file...,您需要使用 JS 或 some CSS like this

引导 4.4

显示选定的文件名也可以使用纯 JavaScript 完成。这是一个假设标准自定义文件输入的示例,其标签是输入的下一个兄弟元素...

document.querySelector('.custom-file-input').addEventListener('change',function(e){
  var fileName = document.getElementById("myInput").files[0].name;
  var nextSibling = e.target.nextElementSibling
  nextSibling.innerText = fileName
})

https://codeply.com/p/LtpNZllird

引导 4.1+

现在在 Bootstrap 4.1 中,“选择文件...”占位符文本设置在 custom-file-label

<div class="custom-file" id="customFile" lang="es">
        <input type="file" class="custom-file-input" id="exampleInputFile" aria-describedby="fileHelp">
        <label class="custom-file-label" for="exampleInputFile">
           Select file...
        </label>
</div>

更改“浏览”按钮文本需要一些额外的 CSS 或 SASS。还要注意language translation works 是如何使用lang="" 属性的。

.custom-file-input ~ .custom-file-label::after {
    content: "Button Text";
}

https://codeply.com/go/gnVCj66Efp (CSS)
https://codeply.com/go/2Mo9OrokBQ (SASS)

另一个 Bootstrap 4.1 选项

您也可以使用这个custom file input plugin

https://www.codeply.com/go/uGJOpHUd8L/file-input


Bootstrap 4 Alpha 6(原始答案)

我认为这里有两个不同的问题..

<label class="custom-file" id="customFile">
        <input type="file" class="custom-file-input">
        <span class="custom-file-control form-control-file"></span>
</label>

1 - 如何更改初始占位符和按钮文本

在 Bootstrap 4 中,initial 占位符值设置在 custom-file-control 上,并使用基于 HTML 语言的 CSS 伪 ::after 元素。初始文件按钮(它实际上不是一个按钮,但看起来像一个按钮)是使用 CSS 伪 ::before 元素设置的。这些值可以被 CSS 覆盖..

#customFile .custom-file-control:lang(en)::after {
  content: "Select file...";
}

#customFile .custom-file-control:lang(en)::before {
  content: "Click me";
}

2 - 如何获取选定的文件名值,并更新输入以显示该值。

选择文件后,可以使用 JavaScript/jQuery 获取值。

$('.custom-file-input').on('change',function(){
    var fileName = $(this).val();
})

但是,由于输入的占位符文本是一个伪元素,there's no easy way to manipulate this with Js/jQuery。但是,您可以使用另一个 CSS 类,在选择文件后隐藏伪内容...

.custom-file-control.selected:lang(en)::after {
  content: "" !important;
}

选择文件后,使用 jQuery 切换 .custom-file-control 上的 .selected 类。这将隐藏初始占位符值。然后把文件名的值放到.form-control-filespan...

$('.custom-file-input').on('change',function(){
  var fileName = $(this).val();
  $(this).next('.form-control-file').addClass("selected").html(fileName);
})

然后您可以根据需要处理文件上传或重新选择。

Demo on Codeply (alpha 6)

【讨论】:

  • C:\fakepath\... 很有趣。
  • 这个C:\fakepath\...来自哪里?
  • @ZimSystem 感谢您的解决方案。我在 Firefox 开发者版中得到相同的 C:\fakepath\..,有没有办法解决这个问题?
  • 我用它来获取没有“fakepath”的文件名:var fileName = document.getElementById("upload-image-input").files[0].name;
  • 我假设它在某个时候发生了变化,但现在您可以通过设置 span 标签的文本来简单地更改可见文本 sn-p
【解决方案2】:

我就是这样解决的

HTML:

<div class="custom-file">
   <input id="logo" type="file" class="custom-file-input">
   <label for="logo" class="custom-file-label text-truncate">Choose file...</label>
</div>

JS:

$('.custom-file-input').on('change', function() { 
   let fileName = $(this).val().split('\\').pop(); 
   $(this).next('.custom-file-label').addClass("selected").html(fileName); 
});

注意:感谢ajax333221 提到.text-truncate 类,如果所选文件名太长,该类将隐藏标签内的溢出。

【讨论】:

  • 感谢.split('\\').pop() 部分!
  • @spaceemotion 很高兴它有帮助
  • FWIW,我必须将type="file" 添加到&lt;input&gt; 标签。但除此之外,效果很好。
  • @ghukill 我的回答是一个快速设计的东西,但我也会添加type 属性,供那些要复制的人使用。谢谢
  • 值得一提的是,您可以像这样 class='custom-file-label text-truncate' 使用 text-truncate 隐藏溢出
【解决方案3】:

Bootstrap 4.3 开始,您可以更改标签标签内的占位符和按钮文本:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />

<div class="custom-file">
  <input type="file" class="custom-file-input" id="exampleInputFile">
  <label class="custom-file-label" for="exampleInputFile" data-browse="{Your button text}">{Your placeholder text}</label>
</div>

【讨论】:

【解决方案4】:

更改文件浏览器的语言:
作为 ZimSystem 提到的(覆盖 CSS)的替代方案,引导文档建议了一个更优雅的解决方案:通过在 SCSS 中添加语言来构建自定义引导样式
在这里阅读:https://getbootstrap.com/docs/4.0/components/forms/#file-browser

注意:您需要在文档中正确设置 lang 属性才能正常工作

用于更新文件选择的值:
你可以像这样使用内联 js:

   <label class="custom-file">
      <input type="file" id="myfile" class="custom-file-input" onchange="$(this).next().after().text($(this).val().split('\\').slice(-1)[0])">
      <span class="custom-file-control"></span>
   </label>

注意.split('\\').slice(-1)[0] 部分删除了 C:\fakepath\ 前缀

【讨论】:

  • 不错。使用它添加到所有自定义文件输入:$('.custom-file-input').change(function () { $(this).next().after().text($(this).val().split('\\').slice(-1)[0]); });
【解决方案5】:

引导程序 4

更多详情herehttps://learncodeweb.com/snippets/browse-button-in-bootstrap-4-with-select-image-preview/

今天我需要创建一个带有多个上传文件选项的浏览按钮,上面所有的 sn-ps 都不适合我。

当我选择多个文件时,official Bootstrap example 也不起作用。

我想出的这段代码将来可能会帮助其他人。

$(document).ready(function() {
  $('input[type="file"]').on("change", function() {
    let filenames = [];
    let files = document.getElementById("customFile").files;
    if (files.length > 1) {
      filenames.push("Total Files (" + files.length + ")");
    } else {
      for (let i in files) {
        if (files.hasOwnProperty(i)) {
          filenames.push(files[i].name);
        }
      }
    }
    $(this)
      .next(".custom-file-label")
      .html(filenames.join(","));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container mt-5">
  <h1 class="text-center">Bootstrap 4 Upload multiple files</h1>
  <div class="col-sm-6 mr-auto ml-auto border p-4">
    <form method="post" enctype="multipart/form-data" action="upload.php">
      <div class="form-group">
        <label><strong>Upload Files</strong></label>
        <div class="custom-file">
          <input type="file" name="files[]" multiple class="custom-file-input form-control" id="customFile">
          <label class="custom-file-label" for="customFile">Choose file</label>
        </div>
      </div>
      <div class="form-group">
        <button type="submit" name="upload" value="upload" id="upload" class="btn btn-block btn-dark"><i class="fa fa-fw fa-upload"></i> Upload</button>
      </div>
    </form>
  </div>
</div>

使用引导程序 3 和引导程序 4.3.1 给出了工作代码示例 here

https://codepen.io/mianzaid/pen/GeEbYV

【讨论】:

  • 实际上,对我来说最有用的答案是+1。小改进:将“form-control”类添加到标签元素。
【解决方案6】:

以防万一,如果您不需要 jquery 解决方案

<label class="custom-file">
      <input type="file" id="myfile" class="custom-file-input" onchange="this.nextElementSibling.innerText = this.files[0].name">
      <span class="custom-file-control"></span>
</label>

【讨论】:

    【解决方案7】:

    这是蓝色 box-shadow,border,outline removed 的答案,在 bootstrap 的自定义文件输入中修复了文件名选择文件名,如果您没有选择任何文件,则显示未选择文件

        $(document).on('change', 'input[type="file"]', function (event) { 
            var filename = $(this).val();
            if (filename == undefined || filename == ""){
            $(this).next('.custom-file-label').html('No file chosen');
            }
            else 
            { $(this).next('.custom-file-label').html(event.target.files[0].name); }
        });
        input[type=file]:focus,.custom-file-input:focus~.custom-file-label {
            outline:none!important;
            border-color: transparent;
            box-shadow: none!important;
        }
        .custom-file,
        .custom-file-label,
        .custom-file-input {
            cursor: pointer;
        }
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
        <div class="container py-5">
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            <span class="input-group-text">Upload</span>
          </div>
          <div class="custom-file">
            <input type="file" class="custom-file-input" id="inputGroupFile01">
            <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
          </div>
        </div>
        </div>

    【讨论】:

      【解决方案8】:

      我只是将它添加到我的 CSS 文件中,它就可以工作:

      .custom-file-label::after{content: 'New Text Button' !important;}
      
      
      

      【讨论】:

        【解决方案9】:

        在jquery的帮助下,可以这样完成。 代码:

        $("input.custom-file-input").on("change",function(){if(this.files.length){var filename=this.file[0].name;if(filename.length>23){filename=filename.substr(0,11)+"..."+filename.substr(-10);}$(this).siblings(".custom-file-label").text(filename);}});
        

        【讨论】:

          【解决方案10】:

          您可以尝试下面给定的 sn-p 以显示从 file 输入类型中选择的文件名。

          document.querySelectorAll('input[type=file]').forEach( input => {
              input.addEventListener('change', e => {
                  e.target.nextElementSibling.innerText = input.files[0].name;
              });
          });
          

          【讨论】:

            【解决方案11】:

            基于@Elnoor 答案的解决方案,但使用多个文件上传表单输入并且没有“fakepath hack”:

            HTML:

            <div class="custom-file">
                <input id="logo" type="file" class="custom-file-input" multiple>
                <label for="logo" class="custom-file-label text-truncate">Choose file...</label>
            </div>
            

            JS:

            $('input[type="file"]').on('change', function () {
                let filenames = [];
                let files = document.getElementById('health_claim_file_form_files').files;
            
                for (let i in files) {
                    if (files.hasOwnProperty(i)) {
                        filenames.push(files[i].name);
                    }
                }
            
                $(this).next('.custom-file-label').addClass("selected").html(filenames.join(',    '));
            });
            

            【讨论】:

              【解决方案12】:

              引导 4.4:

              显示choose file 栏。选择文件后,显示文件名及其扩展名

              <div class="custom-file">
                  <input type="file" class="custom-file-input" id="idEditUploadVideo"
                   onchange="$('#idFileName').html(this.files[0].name)">
                  <label class="custom-file-label" id="idFileName" for="idEditUploadVideo">Choose file</label>
              </div>
              

              【讨论】:

                【解决方案13】:

                如果您想在所有自定义输入上全局使用它,请使用以下 jQuery 代码:

                $(document).ready(function () {
                    $('.custom-file-input').on('change', function (e) {
                         e.target.nextElementSibling.innerHTML = e.target.files[0].name;
                    });
                });
                

                【讨论】:

                  【解决方案14】:

                  对于 Bootstrap v.5

                  document.querySelectorAll('.form-file-input')
                          .forEach(el => el.addEventListener('change', e => e.target.parentElement.querySelector('.form-file-text').innerText = e.target.files[0].name));
                  

                  影响所有文件输入元素。无需指定元素 id。

                  【讨论】:

                    【解决方案15】:

                    对于“bootstrap_4_layout.html.twig”:

                    document.querySelector('.custom-file-input').addEventListener('change',function(e){
                       this.nextElementSibling.innerText = this.files[0].name;
                    });
                    

                    【讨论】:

                      【解决方案16】:
                       <!doctype html>
                      <html lang="en">
                        <head>
                          <!-- Required meta tags -->
                          <meta charset="utf-8">
                          <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
                      
                          <!-- Bootstrap CSS -->
                          <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
                      
                          <title>Hello, world!</title>
                        </head>
                        <body>
                          <h1>Hello, world!</h1>
                        <div class="custom-file">
                          <input type="file" class="custom-file-input" id="inputGroupFile01">
                          <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
                        </div>
                          <!-- Optional JavaScript -->
                          <!-- jQuery first, then Popper.js, then Bootstrap JS -->
                          <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
                          <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
                          <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
                       <script>
                      $(function() {
                        $(document).on('change', ':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]);
                        });
                        $(document).ready( function() {
                            $(':file').on('fileselect', function(event, numFiles, label) {var input = $(this).parents('.custom-file').find('.custom-file-label'),
                            log = numFiles > 1 ? numFiles + ' files selected' : label;if( input.length ) {input.text(log);} else {if( log ) alert(log);}});
                        });
                      });
                       </script>
                        </body>
                      </html>
                      

                      【讨论】:

                        【解决方案17】:

                        没有 JQuery

                        HTML:

                        <INPUT type="file" class="custom-file-input"  onchange="return onChangeFileInput(this);">
                        

                        JS:

                        function onChangeFileInput(elem){
                          var sibling = elem.nextSibling.nextSibling;
                          sibling.innerHTML=elem.value;
                          return true;
                        }
                        

                        克里格

                        【讨论】:

                          猜你喜欢
                          • 2017-10-23
                          • 1970-01-01
                          • 1970-01-01
                          • 2018-08-20
                          • 2018-07-14
                          • 2018-08-25
                          • 2019-05-01
                          • 2019-05-28
                          • 2019-08-02
                          相关资源
                          最近更新 更多