【问题标题】:Twitter Bootstrap Form File Element Upload ButtonTwitter Bootstrap 表单文件元素上传按钮
【发布时间】:2012-06-29 09:59:18
【问题描述】:

为什么 twitter bootstrap 没有花哨的文件元素上传按钮?如果为上传按钮实现了蓝色主按钮,那就太好了。甚至可以使用 CSS 微调上传按钮吗? (看起来像是无法操作的原生浏览器元素)

【问题讨论】:

标签: css forms twitter-bootstrap input-type-file


【解决方案1】:

上传按钮的样式很麻烦,因为它设置了输入而不是按钮的样式。

但你可以使用这个技巧:

http://www.quirksmode.org/dom/inputfile.html

总结:

  1. 取一个普通的<input type="file"> 并把它放在一个带有position: relative 的元素中。

  2. 向同一个父元素添加一个普通的<input> 和一个具有正确样式的图像。绝对定位这些元素,使它们与<input type="file"> 占据相同的位置。

  3. <input type="file"> 的z-index 设置为2,使其位于样式化输入/图像的顶部。

  4. 最后,将<input type="file"> 的不透明度设置为0。<input type="file"> 现在实际上变得不可见,并且样式输入/图像会发光,但您仍然可以单击“浏览”按钮。如果按钮位于图像顶部,则用户似乎单击图像并获得正常的文件选择窗口。 (请注意,您不能使用 visibility: hidden,因为真正不可见的元素也是不可点击的,我们需要保持可点击状态)

【讨论】:

  • 这几天的工作量太大了。在下一个答案中使用像 Jasny 的解决方案这样的现成解决方案更有意义。
  • 如果您的示例包括支持 netscape,它可能不是最新的。
【解决方案2】:

它包含在 Jasny 的 bootstrap 分支中。

可以使用创建一个简单的上传按钮

<span class="btn btn-file">Upload<input type="file" /></span>

使用文件上传插件,您可以创建更高级的小部件。看一下 http://jasny.github.io/bootstrap/javascript/#fileinput

【讨论】:

  • 这在 IE9 中可以正常工作吗?我之所以问,是因为我假设该解决方案使用了 Javascript,同时,“出于安全原因,IE 不允许从 javascript 操作 type=”file” 输入元素。”
  • 是的,它也适用于 IE9。它将输入元素的不透明度设置为 0,幸运的是,它适用于所有浏览器 :)。 quirksmode 文章中对此进行了解释。
  • 它不适用于 jQuery 1.9.0,因为他们放弃了 $.browser 支持
  • 使用常规引导程序看起来很糟糕 - img688.imageshack.us/img688/948/pictureui.png
【解决方案3】:

为我工作:

更新

jQuery plugin style:

// Based in: http://duckranger.com/2012/06/pretty-file-input-field-in-bootstrap/
// Version: 0.0.3
// Compatibility with: Bootstrap 3.2.0 and jQuery 2.1.1
// Use:
//     <input class="nice_file_field" type="file" data-label="Choose Document">
//     <script> $(".nice_file_field").niceFileField(); </script>
//
(function( $ ) {
  $.fn.niceFileField = function() {
    this.each(function(index, file_field) {
      file_field = $(file_field);
      var label = file_field.attr("data-label") || "Choose File";

      file_field.css({"display": "none"});

      nice_file_block_text  = '<div class="input-group nice_file_block">';
      nice_file_block_text += '  <input type="text" class="form-control">';
      nice_file_block_text += '  <span class="input-group-btn">';
      nice_file_block_text += '   <button class="btn btn-default nice_file_field_button" type="button">' + label + '</button>';
      nice_file_block_text += '  </span>';
      nice_file_block_text += '</div>';

      file_field.after(nice_file_block_text);

      var nice_file_field_button = file_field.parent().find(".nice_file_field_button");
      var nice_file_block_element = file_field.parent().find(".nice_file_block");

      nice_file_field_button.on("click", function(){ console.log("click"); file_field.click() } );
      file_field.change( function(){
        nice_file_block_element.find("input").val(file_field.val());
      });
    });
  };
})( jQuery );

【讨论】:

    【解决方案4】:

    不需要额外的插件,这个引导解决方案非常适合我:

    <div style="position:relative;">
            <a class='btn btn-primary' href='javascript:;'>
                Choose File...
                <input type="file" style='position:absolute;z-index:2;top:0;left:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0;background-color:transparent;color:transparent;' name="file_source" size="40"  onchange='$("#upload-file-info").html($(this).val());'>
            </a>
            &nbsp;
            <span class='label label-info' id="upload-file-info"></span>
    </div>
    

    演示:

    http://jsfiddle.net/haisumbhatti/cAXFA/1/(引导程序 2)

    http://jsfiddle.net/haisumbhatti/y3xyU/(引导程序 3)

    【讨论】:

    • 我遇到了一些问题,按钮的底部区域不可点击。这个答案在引导程序 3 中帮助了我:stackoverflow.com/a/18164555/44336
    • 这是一个很好的解决方案,因为它显示了附件的文件名!
    • 有人可以解释一下 href='javascript:;' 的必要性吗?我不需要 onchange='$("#upload-file-info").html($(this).val());'更新 upload-file-info 元素,但如果没有 href,文件上传对话框将不会触发。
    • 'C:\fakepath' 来自哪里,我该如何摆脱它?
    • @Ya。 C:\fakepath 是 html5 安全功能,如果我们使用 javascript 操作它,它会作为文件路径的前缀。有关详细信息,请参阅此博客文章 davidwalsh.name/fakepath
    【解决方案5】:

    这是我最喜欢的文件上传风格:

    <div class="fileupload fileupload-new" data-provides="fileupload">
      <div class="input-append">
        <div class="uneditable-input span3"><i class="icon-file fileupload-exists"></i> <span class="fileupload-preview"></span></div><span class="btn btn-file"><span class="fileupload-new">Select file</span><span class="fileupload-exists">Change</span><input type="file" /></span><a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
      </div>
    </div>
    

    您可以在以下位置获得演示和更多样式:

    http://www.jasny.net/bootstrap/javascript/#fileinput

    但是使用这个,你应该用 jasny 引导文件替换 twitter bootstrap..

    问候。

    【讨论】:

      【解决方案6】:

      不需要花哨的shiz:

      HTML:

      <form method="post" action="/api/admin/image" enctype="multipart/form-data">
          <input type="hidden" name="url" value="<%= boxes[i].url %>" />
          <input class="image-file-chosen" type="text" />
          <br />
          <input class="btn image-file-button" value="Choose Image" />
          <input class="image-file hide" type="file" name="image"/> <!-- Hidden -->
          <br />
          <br />
          <input class="btn" type="submit" name="image" value="Upload" />
          <br />
      </form>
      

      JS:

      $('.image-file-button').each(function() {
            $(this).off('click').on('click', function() {
                 $(this).siblings('.image-file').trigger('click');
            });
      });
      $('.image-file').each(function() {
            $(this).change(function () {
                 $(this).siblings('.image-file-chosen').val(this.files[0].name);
            });
      });
      

      注意:所讨论的三个表单元素必须是彼此的兄弟(.image-file-chosen、.image-file-button、.image-file)

      【讨论】:

        【解决方案7】:

        这非常适合我

        <span>
            <input  type="file" 
                    style="visibility:hidden; width: 1px;" 
                    id='${multipartFilePath}' name='${multipartFilePath}'  
                    onchange="$(this).parent().find('span').html($(this).val().replace('C:\\fakepath\\', ''))"  /> <!-- Chrome security returns 'C:\fakepath\'  -->
            <input class="btn btn-primary" type="button" value="Upload File.." onclick="$(this).parent().find('input[type=file]').click();"/> <!-- on button click fire the file click event -->
            &nbsp;
            <span  class="badge badge-important" ></span>
        </span>
        

        【讨论】:

          【解决方案8】:

          这是 Bootstrap 3、4 和 5 的解决方案。

          要制作一个看起来像按钮的功能文件输入控件,只需要 HTML:

          HTML

          <label class="btn btn-default">
              Browse <input type="file" hidden>
          </label>
          

          这适用于所有现代浏览器,包括 IE9+。如果您还需要对旧版 IE 的支持,请使用下面显示的旧版方法。

          此技术依赖于 HTML5 hidden 属性。 Bootstrap 4 使用以下 CSS 在不支持的浏览器中填充此功能。如果您使用的是 Bootstrap 3,则可能需要添加。

          [hidden] {
            display: none !important;
          }
          

          旧 IE 的遗留方法

          如果您需要支持 IE8 及以下版本,请使用以下 HTML/CSS:

          HTML

          <span class="btn btn-default btn-file">
              Browse <input type="file">
          </span>
          

          CSS

          .btn-file {
              position: relative;
              overflow: hidden;
          }
          .btn-file input[type=file] {
              position: absolute;
              top: 0;
              right: 0;
              min-width: 100%;
              min-height: 100%;
              font-size: 100px;
              text-align: right;
              filter: alpha(opacity=0);
              opacity: 0;
              outline: none;
              background: white;
              cursor: inherit;
              display: block;
          }
          

          请注意,当您单击 &lt;label&gt; 时,旧的 IE 不会触发文件输入,因此 CSS“膨胀”做了几件事来解决这个问题:

          • 使文件输入跨越周围&lt;span&gt;的整个宽度/高度
          • 使文件输入不可见

          反馈和补充阅读

          我已经发布了有关此方法的更多详细信息,以及如何向用户显示选择了哪些/多少文件的示例:

          https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/

          【讨论】:

          • + 1 对我来说,这是迄今为止最好的答案。使用最新版本的引导程序非常简洁的解决方案。
          • @Ulises @JaredEitnier @IvanWang 我非常不同意。并为my answer 提供一个无耻的插件,它只使用&lt;label&gt; 元素。作为最好的解决方案:)
          • 我必须同意@KirillFuchs;标签会更好。另外 - 用户看不到他们是否选择了正确的文件,因为按钮没有显示选择的文件名:jsfiddle.net/36o9pdf9/1
          • 标签在语义上会更好。查看文章以了解显示哪些文件被选中的方法。 (某些应用会在选择文件时自动上传,因此在这些情况下,文件名反馈并不重要。)
          • 我无法让它与 FormData 对象一起在 IE11 上工作。不知何故,当输入字段位于标签元素内时,IE 会忽略输入字段,因此无法从 FormData 对象中获得文件数据。
          【解决方案9】:

          http://markusslima.github.io/bootstrap-filestyle/

          $(":file").filestyle();
          

          <input type="file" class="filestyle" data-input="false">
          

          【讨论】:

            【解决方案10】:

            /* * Bootstrap 3 文件样式 * http://dev.tudosobreweb.com.br/bootstrap-filestyle/ * * 版权所有 (c) 2013 Markus Vinicius da Silva Lima * Paulo Henrique Foxer 更新 bootstrap 3 * 版本 2.0.0 * 在 MIT 许可下获得许可。 * */

            (function ($) {
            "use strict";
            
            var Filestyle = function (element, options) {
                this.options = options;
                this.$elementFilestyle = [];
                this.$element = $(element);
            };
            
            Filestyle.prototype = {
                clear: function () {
                    this.$element.val('');
                    this.$elementFilestyle.find(':text').val('');
                },
            
                destroy: function () {
                    this.$element
                        .removeAttr('style')
                        .removeData('filestyle')
                        .val('');
                    this.$elementFilestyle.remove();
                },
            
                icon: function (value) {
                    if (value === true) {
                        if (!this.options.icon) {
                            this.options.icon = true;
                            this.$elementFilestyle.find('label').prepend(this.htmlIcon());
                        }
                    } else if (value === false) {
                        if (this.options.icon) {
                            this.options.icon = false;
                            this.$elementFilestyle.find('i').remove();
                        }
                    } else {
                        return this.options.icon;
                    }
                },
            
                input: function (value) {
                    if (value === true) {
                        if (!this.options.input) {
                            this.options.input = true;
                            this.$elementFilestyle.prepend(this.htmlInput());
            
                            var content = '',
                                files = [];
                            if (this.$element[0].files === undefined) {
                                files[0] = {'name': this.$element[0].value};
                            } else {
                                files = this.$element[0].files;
                            }
            
                            for (var i = 0; i < files.length; i++) {
                                content += files[i].name.split("\\").pop() + ', ';
                            }
                            if (content !== '') {
                                this.$elementFilestyle.find(':text').val(content.replace(/\, $/g, ''));
                            }
                        }
                    } else if (value === false) {
                        if (this.options.input) {
                            this.options.input = false;
                            this.$elementFilestyle.find(':text').remove();
                        }
                    } else {
                        return this.options.input;
                    }
                },
            
                buttonText: function (value) {
                    if (value !== undefined) {
                        this.options.buttonText = value;
                        this.$elementFilestyle.find('label span').html(this.options.buttonText);
                    } else {
                        return this.options.buttonText;
                    }
                },
            
                classButton: function (value) {
                    if (value !== undefined) {
                        this.options.classButton = value;
                        this.$elementFilestyle.find('label').attr({'class': this.options.classButton});
                        if (this.options.classButton.search(/btn-inverse|btn-primary|btn-danger|btn-warning|btn-success/i) !== -1) {
                            this.$elementFilestyle.find('label i').addClass('icon-white');
                        } else {
                            this.$elementFilestyle.find('label i').removeClass('icon-white');
                        }
                    } else {
                        return this.options.classButton;
                    }
                },
            
                classIcon: function (value) {
                    if (value !== undefined) {
                        this.options.classIcon = value;
                        if (this.options.classButton.search(/btn-inverse|btn-primary|btn-danger|btn-warning|btn-success/i) !== -1) {
                            this.$elementFilestyle.find('label').find('i').attr({'class': 'icon-white '+this.options.classIcon});
                        } else {
                            this.$elementFilestyle.find('label').find('i').attr({'class': this.options.classIcon});
                        }
                    } else {
                        return this.options.classIcon;
                    }
                },
            
                classInput: function (value) {
                    if (value !== undefined) {
                        this.options.classInput = value;
                        this.$elementFilestyle.find(':text').addClass(this.options.classInput);
                    } else {
                        return this.options.classInput;
                    }
                },
            
                htmlIcon: function () {
                    if (this.options.icon) {
                        var colorIcon = '';
                        if (this.options.classButton.search(/btn-inverse|btn-primary|btn-danger|btn-warning|btn-success/i) !== -1) {
                            colorIcon = ' icon-white ';
                        }
            
                        return '<i class="'+colorIcon+this.options.classIcon+'"></i> ';
                    } else {
                        return '';
                    }
                },
            
                htmlInput: function () {
                    if (this.options.input) {
                        return '<input type="text" class="'+this.options.classInput+'" style="width: '+this.options.inputWidthPorcent+'% !important;display: inline !important;" disabled> ';
                    } else {
                        return '';
                    }
                },
            
                constructor: function () {
                    var _self = this,
                        html = '',
                        id = this.$element.attr('id'),
                        files = [];
            
                    if (id === '' || !id) {
                        id = 'filestyle-'+$('.bootstrap-filestyle').length;
                        this.$element.attr({'id': id});
                    }
            
                    html = this.htmlInput()+
                         '<label for="'+id+'" class="'+this.options.classButton+'">'+
                            this.htmlIcon()+
                            '<span>'+this.options.buttonText+'</span>'+
                         '</label>';
            
                    this.$elementFilestyle = $('<div class="bootstrap-filestyle" style="display: inline;">'+html+'</div>');
            
                    var $label = this.$elementFilestyle.find('label');
                    var $labelFocusableContainer = $label.parent();
            
                    $labelFocusableContainer
                        .attr('tabindex', "0")
                        .keypress(function(e) {
                            if (e.keyCode === 13 || e.charCode === 32) {
                                $label.click();
                            }
                        });
            
                    // hidding input file and add filestyle
                    this.$element
                        .css({'position':'absolute','left':'-9999px'})
                        .attr('tabindex', "-1")
                        .after(this.$elementFilestyle);
            
                    // Getting input file value
                    this.$element.change(function () {
                        var content = '';
                        if (this.files === undefined) {
                            files[0] = {'name': this.value};
                        } else {
                            files = this.files;
                        }
            
                        for (var i = 0; i < files.length; i++) {
                            content += files[i].name.split("\\").pop() + ', ';
                        }
            
                        if (content !== '') {
                            _self.$elementFilestyle.find(':text').val(content.replace(/\, $/g, ''));
                        }
                    });
            
                    // Check if browser is Firefox
                    if (window.navigator.userAgent.search(/firefox/i) > -1) {
                        // Simulating choose file for firefox
                        this.$elementFilestyle.find('label').click(function () {
                            _self.$element.click();
                            return false;
                        });
                    }
                }
            };
            
            var old = $.fn.filestyle;
            
            $.fn.filestyle = function (option, value) {
                var get = '',
                    element = this.each(function () {
                        if ($(this).attr('type') === 'file') {
                            var $this = $(this),
                                data = $this.data('filestyle'),
                                options = $.extend({}, $.fn.filestyle.defaults, option, typeof option === 'object' && option);
            
                            if (!data) {
                                $this.data('filestyle', (data = new Filestyle(this, options)));
                                data.constructor();
                            }
            
                            if (typeof option === 'string') {
                                get = data[option](value);
                            }
                        }
                    });
            
                if (typeof get !== undefined) {
                    return get;
                } else {
                    return element;
                }
            };
            
            $.fn.filestyle.defaults = {
                'buttonText': 'Escolher arquivo',
                'input': true,
                'icon': true,
                'inputWidthPorcent': 65,
                'classButton': 'btn btn-primary',
                'classInput': 'form-control file-input-button',
                'classIcon': 'icon-folder-open'
            };
            
            $.fn.filestyle.noConflict = function () {
                $.fn.filestyle = old;
                return this;
            };
            
            // Data attributes register
            $('.filestyle').each(function () {
                var $this = $(this),
                    options = {
                        'buttonText': $this.attr('data-buttonText'),
                        'input': $this.attr('data-input') === 'false' ? false : true,
                        'icon': $this.attr('data-icon') === 'false' ? false : true,
                        'classButton': $this.attr('data-classButton'),
                        'classInput': $this.attr('data-classInput'),
                        'classIcon': $this.attr('data-classIcon')
                    };
            
                $this.filestyle(options);
            });
            })(window.jQuery);
            

            【讨论】:

              【解决方案11】:

              一个结果可接受的简单解决方案:

              <input type="file" class="form-control">
              

              还有风格:

              input[type=file].form-control {
                  height: auto;
              }
              

              【讨论】:

                【解决方案12】:

                我有同样的问题,我尝试这样。

                <div>
                <button type='button' class='btn btn-info btn-file'>Browse</button>
                <input type='file' name='image'/>
                </div>
                

                CSS

                <style>
                .btn-file {
                    position:absolute;
                }
                </style>
                

                JS

                <script>
                $(document).ready(function(){
                    $('.btn-file').click(function(){
                        $('input[name="image"]').click();
                    });
                });
                </script>
                

                注意: 按钮 .btn-file 必须与输入文件在同一标签中

                希望您找到最佳解决方案...

                【讨论】:

                  【解决方案13】:

                  我用http://gregpike.net/demos/bootstrap-file-input/demo.html:

                  $('input[type=file]').bootstrapFileInput();
                  

                  $('.file-inputs').bootstrapFileInput();
                  

                  【讨论】:

                  • 使用 cmets 获得微小的答案或建议。
                  【解决方案14】:

                  我很惊讶没有提到 &lt;label&gt; 元素。

                  解决方案:

                  <label class="btn btn-primary" for="my-file-selector">
                      <input id="my-file-selector" type="file" class="d-none">
                      Button Text Here
                  </label>
                  

                  不需要任何 JS 或时髦的 css...

                  包含文件名的解决方案:

                  <label class="btn btn-primary" for="my-file-selector">
                      <input id="my-file-selector" type="file" style="display:none" 
                      onchange="$('#upload-file-info').text(this.files[0].name)">
                      Button Text Here
                  </label>
                  <span class='label label-info' id="upload-file-info"></span>
                  

                  上面的解决方案需要 jQuery。

                  注意:在页面上显示用户提供的内容时使用$.text()。这个答案的早期版本使用了$.html(),这是不安全的——文件名可以包含 HTML 标记。

                  【讨论】:

                  • 这个答案应该是被接受的。它甚至比@claviska 的答案更好
                  • 不太明白为什么这不是公认的答案。干净、简单、稳定(除非你的目标是
                  • 我无法让它与 FormData 对象一起在 IE11 上工作。不知何故,当输入字段位于标签元素内时,IE 会忽略输入字段,因此无法从 FormData 对象中获得文件数据。
                  • 好吧,它不显示选择了哪个文件(
                  • 如果您使用标签包装目标元素,则无需使用for
                  【解决方案15】:

                  从上面的其他帖子中获得一些灵感,这里有一个完整的解决方案,它将看起来像表单控制字段的内容与输入组插件相结合,用于包含指向当前文件的链接的干净文件输入小部件。

                  .input-file { position: relative; margin: 60px 60px 0 } /* Remove margin, it is just for stackoverflow viewing */
                  .input-file .input-group-addon { border: 0px; padding: 0px; }
                  .input-file .input-group-addon .btn { border-radius: 0 4px 4px 0 }
                  .input-file .input-group-addon input { cursor: pointer; position:absolute; width: 72px; z-index:2;top:0;right:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0; background-color:transparent; color:transparent; }
                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
                  <div class="input-group input-file">
                    <div class="form-control">
                      <a href="/path/to/your/current_file_name.pdf" target="_blank">current_file_name.pdf</a>
                    </div>
                    <span class="input-group-addon">
                      <a class='btn btn-primary' href='javascript:;'>
                        Browse
                        <input type="file" name="field_name" onchange="$(this).parent().parent().parent().find('.form-control').html($(this).val());">
                      </a>
                    </span>
                  </div>

                  【讨论】:

                    【解决方案16】:

                    在 Bootstrap v.3.3.4 中尝试以下操作

                    <div>
                        <input id="uplFile" type="file" style="display: none;">
                    
                        <div class="input-group" style="width: 300px;">
                            <div  id="btnBrowse"  class="btn btn-default input-group-addon">Select a file...</div>
                            <span id="photoCover" class="form-control">
                        </div>
                    </div>
                    
                    <script type="text/javascript">
                        $('#uplFile').change(function() {
                            $('#photoCover').text($(this).val());
                        });
                    
                        $('#btnBrowse').click(function(){
                            $('#uplFile').click();
                        });
                    </script>
                    

                    【讨论】:

                      【解决方案17】:

                      请查看Twitter Bootstrap File Input。 它使用非常简单的解决方案,只需添加一个 javascript 文件并粘贴以下代码:

                      $('input[type=file]').bootstrapFileInput();
                      

                      【讨论】:

                      • 链接已损坏(2019 年 7 月)
                      • @Yetti99 是的,它现在坏了
                      • @Yetti99,我更改了链接。请立即检查。
                      【解决方案18】:

                      使用其他答案的部分简化答案,主要是 user2309766 和 dotcomsuperstar。

                      特点:

                      • 为按钮和字段使用 Bootstrap 按钮插件。
                      • 只有一个输入;多个输入将被一个表单拾取。
                      • 除了“display: none;”没有额外的css隐藏文件输入。
                      • 可见按钮触发隐藏文件输入的点击事件。
                      • split 删除文件路径使用正则表达式和分隔符 '\' 和 '/'。

                      代码:

                      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
                      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
                      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                      
                      <div class="input-group">
                        <span class="input-group-btn">
                          <span class="btn btn-primary" onclick="$(this).parent().find('input[type=file]').click();">Browse</span>
                          <input name="uploaded_file" onchange="$(this).parent().parent().find('.form-control').html($(this).val().split(/[\\|/]/).pop());" style="display: none;" type="file">
                        </span>
                        <span class="form-control"></span>
                      </div>

                      【讨论】:

                        【解决方案19】:

                        这是一个替代技巧,它不是最好的解决方案,但它只是给你一个选择

                        HTML 代码:

                        <button clss="btn btn-primary" id="btn_upload">Choose File</button>
                        <input id="fileupload" class="hide" type="file" name="files[]">
                        

                        Javascript:

                        $("#btn_upload").click(function(e){
                        e.preventDefault();
                        $("#fileupload").trigger('click');
                        });
                        

                        【讨论】:

                          【解决方案20】:

                          我创建了一个自定义上传按钮,只接受图片,可以根据您的要求进行修改。

                          希望这会有所帮助! :)

                          (使用 Bootstrap 框架)

                          Codepen-link

                          HTML

                          <center>
                           <br />
                           <br />
                           <span class="head">Upload Button Re-Imagined</span>
                           <br />
                           <br />
                           <div class="fileUpload blue-btn btn width100">
                             <span>Upload your Organizations logo</span>
                             <input type="file" class="uploadlogo" />
                           </div>
                          </center>
                          

                          CSS

                           .head {
                             font-size: 25px;
                             font-weight: 200;
                           }
                          
                           .blue-btn:hover,
                           .blue-btn:active,
                           .blue-btn:focus,
                           .blue-btn {
                             background: transparent;
                             border: solid 1px #27a9e0;
                             border-radius: 3px;
                             color: #27a9e0;
                             font-size: 16px;
                             margin-bottom: 20px;
                             outline: none !important;
                             padding: 10px 20px;
                           }
                          
                           .fileUpload {
                             position: relative;
                             overflow: hidden;
                             height: 43px;
                             margin-top: 0;
                           }
                          
                           .fileUpload input.uploadlogo {
                             position: absolute;
                             top: 0;
                             right: 0;
                             margin: 0;
                             padding: 0;
                             font-size: 20px;
                             cursor: pointer;
                             opacity: 0;
                             filter: alpha(opacity=0);
                             width: 100%;
                             height: 42px;
                           }
                          
                          
                           /*Chrome fix*/
                          
                           input::-webkit-file-upload-button {
                             cursor: pointer !important;
                           }
                          

                          JS

                          // You can modify the upload files to pdf's, docs etc
                          //Currently it will upload only images
                          $(document).ready(function($) {
                          
                            // Upload btn
                            $(".uploadlogo").change(function() {
                              readURL(this);
                            });
                          
                            function readURL(input) {
                              var url = input.value;
                              var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
                              if (input.files && input.files[0] && (ext == "png" || ext == "jpeg" || ext == "jpg" || ext == "gif" || ext == "svg")) {
                                var path = $('.uploadlogo').val();
                                var filename = path.replace(/^.*\\/, "");
                                $('.fileUpload span').html('Uploaded logo : ' + filename);
                                // console.log(filename);
                              } else {
                                $(".uploadlogo").val("");
                                $('.fileUpload span').html('Only Images Are Allowed!');
                              }
                            }
                          });
                          

                          【讨论】:

                            【解决方案21】:

                            我修改了@claviska 的答案并按我喜欢的方式工作(Bootstrap 3、4 未测试):

                            <label class="btn btn-default">
                                <span>Browse</span>
                                <input type="file" style="display: none;" onchange="$(this).prev('span').text($(this).val()!=''?$(this).val():'Browse')">
                            </label>
                            

                            【讨论】:

                              【解决方案22】:

                              以下代码如上图所示

                              HTML

                              <form>
                              <div class="row">
                              <div class="col-lg-6">
                              <label for="file">
                              <div class="input-group">
                              <span class="input-group-btn">
                              <button class="btn btn-default" type="button">Browse</button>
                              </span>
                              <input type="text" class="form-control" id="info" readonly="" style="background: #fff;" placeholder="Search for...">
                              </div><!-- /input-group -->
                              </label>
                              </div><!-- /.col-lg-6 -->
                              </div>
                              
                              </div>
                              <input type="file" style="display: none;" onchange="$('#info').val($(this).val().split(/[\\|/]/).pop()); " name="file" id="file">
                              </form>
                              

                              Javascript

                              <script type="text/javascript">
                              
                              $(function() {
                                  $("label[for=file]").click(function(event) {
                                      event.preventDefault();
                                      $("#file").click();
                                  });
                              });
                              
                              </script>
                              

                              【讨论】:

                                【解决方案23】:

                                多次上传解决方案

                                我调整了之前的两个答案以包含多个上传。这样标签显示文件名,如果只选择一个,或者x files在相反的情况下。

                                <label class="btn btn-primary" for="my-file-selector">
                                    <input id="my-file-selector" type="file" multiple="multiple" style="display:none"
                                        onchange="$('#upload-file-info').html(
                                            (this.files.length > 1) ? this.files.length + ' files' : this.files[0].name)">                     
                                    Files&hellip;
                                </label>
                                <span class='label label-info' id="upload-file-info"></span>
                                

                                它也可能适用于更改按钮文本和类。

                                <label class="btn btn-primary" for="multfile">
                                    <input id="multfile" type="file" multiple="multiple" style="display:none"
                                        onchange="$('#multfile-label').html(
                                            (this.files.length == 1) ? this.files[0].name : this.files.length + ' files');
                                            $(this).parent().addClass('btn-success')">
                                    <span id="multfile-label">Files&hellip;</span>
                                </label>
                                

                                【讨论】:

                                  【解决方案24】:

                                  关于 claviska 答案 - 如果您想在基本文件上传中显示上传的文件名,您可以在输入的 onchange 事件中进行。只需使用此代码:

                                   <label class="btn btn-default">
                                                      Browse...
                                                      <span id="uploaded-file-name" style="font-style: italic"></span>
                                                      <input id="file-upload" type="file" name="file"
                                                             onchange="$('#uploaded-file-name').text($('#file-upload')[0].value);" hidden>
                                   </label>
                                  

                                  这个 jquery JS 代码负责检索上传的文件名:

                                  $('#file-upload')[0].value
                                  

                                  或者使用香草 JS:

                                  document.getElementById("file-upload").value
                                  

                                  【讨论】:

                                    【解决方案25】:

                                    我想我会加上我的三便士价值,只是说默认.custom-file-labelcustom-file-input BS4文件输入以及如何使用。

                                    后一个类在输入组上并且不可见。而前者是可见标签,并且有一个看起来像按钮的 :after 伪元素。

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

                                    您不能向伪元素添加类,但可以在 CSS(或 SASS)中设置它们的样式。

                                    .custom-file-label:after {
                                        color: #fff;
                                        background-color: #1e7e34;
                                        border-color: #1c7430;
                                        pointer: cursor;
                                    }
                                    

                                    【讨论】:

                                      【解决方案26】:

                                      基于绝对出色的@claviska 解决方案,所有功劳都归功于他。

                                      带有验证和帮助文本的全功能 Bootstrap 4 文件输入。

                                      基于input group example,我们有一个用于向用户显示文件名的虚拟输入文本字段,该字段由隐藏在标签按钮后面的实际输入文件字段上的onchange 事件填充。除了包括bootstrap 4 validation 支持外,我们还可以单击输入中的任意位置以打开文件对话框。

                                      文件输入的三种状态

                                      三种可能的状态是未验证、有效和无效,并设置了虚拟 html 输入标记属性required

                                      输入的 HTML 标记

                                      我们只引入了 2 个自定义类 input-file-dummyinput-file-btn 来正确设置和连接所需的行为。其他一切都是标准的 Bootstrap 4 标记。

                                      <div class="input-group">
                                        <input type="text" class="form-control input-file-dummy" placeholder="Choose file" aria-describedby="fileHelp" required>
                                        <div class="valid-feedback order-last">File is valid</div>
                                        <div class="invalid-feedback order-last">File is required</div>
                                        <label class="input-group-append mb-0">
                                          <span class="btn btn-primary input-file-btn">
                                            Browse… <input type="file" hidden>
                                          </span>
                                        </label>
                                      </div>
                                      <small id="fileHelp" class="form-text text-muted">Choose any file you like</small>
                                      

                                      JavaScript 行为规定

                                      根据原始示例,虚拟输入需要只读,以防止用户更改只能通过打开文件对话框更改的输入。不幸的是,readonly 字段不会进行验证,因此我们在焦点和模糊(jquery eventsonfocusinonfocusout)上切换输入的可编辑性,并确保在选择文件后再次变为可验证。

                                      除了使文本字段可点击之外,通过触发按钮的点击事件,填充虚拟字段的其余功能由@claviska 设想。

                                      $(function () {
                                        $('.input-file-dummy').each(function () {
                                          $($(this).parent().find('.input-file-btn input')).on('change', {dummy: this}, function(ev) {
                                            $(ev.data.dummy)
                                              .val($(this).val().replace(/\\/g, '/').replace(/.*\//, ''))
                                              .trigger('focusout');
                                          });
                                          $(this).on('focusin', function () {
                                              $(this).attr('readonly', '');
                                            }).on('focusout', function () {
                                              $(this).removeAttr('readonly');
                                            }).on('click', function () {
                                              $(this).parent().find('.input-file-btn').click();
                                            });
                                        });
                                      });
                                      

                                      自定义样式调整

                                      最重要的是,我们不希望 readonly 字段在灰色背景和白色之间跳转,因此我们确保它保持白色。 span 按钮没有指针光标,但无论如何我们都需要为输入添加一个。

                                      .input-file-dummy, .input-file-btn {
                                        cursor: pointer;
                                      }
                                      .input-file-dummy[readonly] {
                                        background-color: white;
                                      }
                                      

                                      开心!

                                      【讨论】:

                                        猜你喜欢
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2014-05-06
                                        • 2014-01-09
                                        • 1970-01-01
                                        • 2012-10-18
                                        • 2013-12-11
                                        • 1970-01-01
                                        • 2013-01-12
                                        相关资源
                                        最近更新 更多