Javascript Bootstrap 4 文件输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43250263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:47:03  来源:igfitidea点击:

Bootstrap 4 File Input

javascriptjquerycsstwitter-bootstrapbootstrap-4

提问by Matej Vrzala M4

I am struggling with bootstrap 4 file browser. If I use custom-file-control I will see Choose file value all the time. https://v4-alpha.getbootstrap.com/components/forms/#file-browser

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

I would like to change the value of choose file after the file has been chosen. This value is actually hidden in css .custom-file-control:lang(en)::afterand I do not know how to access and change it in javascript. I can get the value of chosen file like this:

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

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

not I need to change

不是我需要改变

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

somehow

不知何故

link: http://codepen.io/Matoo125/pen/LWobNp

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

回答by Zim

Updated 2016

2016 年更新

Bootstrap 4.4

引导程序 4.4

Displaying the selected filename can also be done with plain JavaScript. Here's an example that assumes the standard custom-file-input with label that is the next sibling element to the input...

也可以使用纯 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

https://codeply.com/p/LtpNZllird

Bootstrap 4.1+

引导程序 4.1+

Now in Bootstrap 4.1 the "Choose file..." placeholder text is set in the custom-file-label:

现在在 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>

Changing the "Browse" button text requires a little extra CSS or SASS. Also notice how language translation worksusing the lang=""attribute.

更改“浏览”按钮文本需要一点额外的 CSS 或 SASS。还要注意语言翻译是如何使用该lang=""属性进行的。

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

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

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

Another Bootstrap 4.1 Option

另一个 Bootstrap 4.1 选项

Alternatively you can use this custom file input plugin

或者,您可以使用此自定义文件输入插件

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

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



Bootstrap 4 Alpha 6(Original Answer)

Bootstrap 4 Alpha 6(原始答案)

I think there are 2 separate issues here..

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

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

1 - How the change the initial placeholder and button text

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

In Bootstrap 4, the initialplaceholder value is set on the custom-file-controlwith a CSS pseudo ::afterelement based on the HTML language. The initial file button (which isn't really a button but looks like one) is set with a CSS pseudo ::beforeelement. These values can be overridden with CSS..

在 Bootstrap 4 中,初始占位符值设置在基于 HTML 语言custom-file-control的 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 - How to get the selected filename value, and update the input to show the value.

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

Once a file is selected, the value can be obtained using JavaScript/jQuery.

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

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

However, since the placeholder text for the input is a pseudo element, there's no easy way to manipulate this with Js/jQuery. You can however, have a another CSS class that hides the pseudo contentonce the file is selected...

但是,由于输入的占位符文本是一个伪元素,因此没有简单的方法可以使用 Js/jQuery 来操作它。但是,您可以使用另一个 CSS 类,选择文件后隐藏伪内容...

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

Use jQuery to toggle the .selectedclass on the .custom-file-controlonce the file is selected. This will hide the initial placeholder value. Then put the filename value in the .form-control-filespan...

选择文件后,使用 jQuery 切换.selected.custom-file-control。这将隐藏初始占位符值。然后将文件名值放入.form-control-file跨度...

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

You can then handle the file upload or re-selection as needed.

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

Demo on Codeply (alpha 6)

Codeply 上的演示(alpha 6)

回答by Elnoor

I just solved it this way

我就是这样解决的

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:

JS:

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

Note: Thanks to ajax333221for mentioning the .text-truncateclass that will hide the overflow within label if the selected file name is too long.

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

回答by Andrei Veshtard

As of Bootstrap 4.3you can change placeholder and button text inside the label tag:

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>

回答by Razvan Pocaznoi

For changing the language of the file browser:
As an alternate to what ZimSystemmentioned (override the CSS), a more elegant solution is suggested by the bootstrap docs: build your custom bootstrap styles by adding languages in SCSS
Read about it here: https://getbootstrap.com/docs/4.0/components/forms/#file-browser

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

Note: you need to have the lang attribute properly set in your document for this to work

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

For updating the value on file selection:
You could do it with inline js like this:

更新文件选择的值:
您可以使用内联 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>

Note: the .split('\\').slice(-1)[0]part removes the C:\fakepath\prefix

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

回答by Zaid Bin Khalid

Bootstrap 4

引导程序 4

More details are herehttps://learncodeweb.com/snippets/browse-button-in-bootstrap-4-with-select-image-preview/

更多细节在这里https://learncodeweb.com/snippets/browse-button-in-bootstrap-4-with-select-image-preview/

Today I need to create a browse button with multi-upload files option all above snippets are not good for me.

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

The official Bootstrap exampleis also not working when I select multiple files.

当我选择多个文件时,官方 Bootstrap 示例也不起作用。

I come up with this code may be will help others in the future.

我想出这个代码可能会在未来帮助其他人。

<div class="container mt-5">
  <h1 class="text-center">Bootstrap 4 Upload multiple files</h1>
  <div class="col-sm-4 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>

The js code is given below.

js代码如下。

$(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(","));
  });
});

The working code example is given herewith bootstrap 3 and bootstrap 4.3.1.

此处给出带有 bootstrap 3 和 bootstrap 4.3.1的工作代码示例。

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

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

回答by sakhimpungose

With the help of jquery, it can be done like this. Code:

在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);}});

回答by codex fast

You can try below given snippet to display the selected file name from the fileinput type.

您可以尝试在下面给定的代码段中显示从文件输入类型中选择的文件名。

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

回答by Soham Patel

Here is the answer with blue box-shadow,border,outline removedwith file name fix in custom-file input of bootstrapappear on choose filenameand if you not choose any file then show No file chosen.

这是在bootstrap 的自定义文件输入中删除带有文件名修复的蓝色框阴影、边框、轮廓的答案,出现在选择文件名上,如果您未选择任何文件,则显示No file selected

    $(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>

回答by Robson Sousa

I just add this in my CSS file and it works:

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

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


回答by Sicaa

Solution based on @Elnoor answer, but working with multiple file upload form input and without the "fakepath hack":

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

HTML:

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:

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(',    '));
});