Кнопка загрузки элемента формы файла Twitter Bootstrap

498

Почему в загрузчике Twitter нет красивой кнопки загрузки элемента? Было бы здорово, если бы для кнопки загрузки была реализована синяя основная кнопка. Можно ли даже отточить кнопку загрузки с помощью CSS? (похоже на нативный элемент браузера, которым нельзя манипулировать)

Теги:
forms
input-type-file

26 ответов

901
Лучший ответ

Вот решение для Bootstrap 3 и 4.

Чтобы создать элемент управления входным файлом, который выглядит как кнопка, вам нужен только 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;
}

Обратите внимание, что старый IE не запускает ввод файла, когда вы нажимаете <label>, поэтому CSS "bloat" делает пару вещей, чтобы обойти это:

  • Делает диапазон ввода файла полной шириной/высотой окружающего <span>
  • Делает входной файл невидимым

Обратная связь и дополнительное чтение

Я разместил более подробные сведения об этом методе, а также примеры того, как отображать пользователя, которое/сколько файлов выбрано:

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

  • 51
    +1 Для меня это лучший ответ. Очень краткое решение с использованием последней версии начальной загрузки.
  • 0
    @ qub1n Перейдите по ссылке на статью, чтобы узнать, как это сделать.
Показать ещё 25 комментариев
333

Я удивился, что не упоминалось о элементе <label>.

Решение:

<label class="btn btn-primary" for="my-file-selector">
    <input id="my-file-selector" type="file" style="display: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').html(this.files[0].name)">
    Button Text Here
</label>
<span class='label label-info' id="upload-file-info"></span>

Для решения выше требуется jQuery.

  • 34
    Этот ответ должен быть принятым. Это даже лучше, чем ответ @ claviska
  • 0
    Приятное прикосновение с помощью этикетки. Мне придется проверить поддержку устаревшего браузера. Вам также все еще понадобится JS, если вы хотите показать выбранные файлы (хотя я подозреваю, что большинство приложений автоматически загружаются, как только выбор сделан).
Показать ещё 22 комментария
128

Без дополнительного плагина это решение для бутстрапа отлично работает для меня:

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

demo:

http://jsfiddle.net/haisumbhatti/cAXFA/1/ (bootstrap 2)

Изображение 2312

http://jsfiddle.net/haisumbhatti/y3xyU/ (bootstrap 3)

Изображение 2313

  • 6
    У меня были некоторые проблемы с нижней частью кнопки, не нажимаемой. Этот ответ помог мне в начальной загрузке 3: stackoverflow.com/a/18164555/44336
  • 3
    Это отличное решение, так как показывает имя файла в прикрепленном файле!
Показать ещё 4 комментария
91

Он включен в вилку Ясного бутстрапа.

Простую кнопку загрузки можно создать с помощью

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

С помощью плагина fileupload вы можете создавать более продвинутые виджеты. Посмотри на http://jasny.github.io/bootstrap/javascript/#fileinput

  • 0
    Это хорошо работает в IE9? Я спрашиваю, потому что я предполагаю, что решение использует Javascript, и в то же время «IE не позволяет манипулировать элементом ввода type =” file ”из javascript по соображениям безопасности».
  • 0
    Да, это работает и в IE9. Он устанавливает непрозрачность элемента ввода в 0, что, к счастью, работает во всех браузерах :). Это объясняется в статье "Причудливый режим".
Показать ещё 3 комментария
62

Кнопки загрузки - это стиль боли, потому что он стилирует вход, а не кнопку.

но вы можете использовать этот трюк:

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

Резюме:

  • Возьмите нормальный <input type="file"> и поместите его в элемент с position: relative.

  • В этот же родительский элемент добавьте нормальный <input> и изображение, имеющее правильные стили. Поместите эти элементы абсолютно, чтобы они занимали то же место, что и <input type="file">.

  • Установите z-индекс <input type="file"> в 2, чтобы он лежал поверх стилизованного ввода/изображения.

  • Наконец, установите непрозрачность <input type="file"> на 0. Теперь <input type="file"> становится невидимым, а стили ввода/изображения светятся, но вы все равно можете нажать кнопку "Обзор". Если кнопка расположена поверх изображения, пользователь, как ожидается, нажимает на изображение и получает окно выбора нормального файла. (Обратите внимание, что вы не можете использовать видимость: скрытый, потому что действительно невидимый элемент тоже незаменим, и нам нужно, чтобы он оставался кликабельным)

  • 6
    Это слишком много работы в эти дни. Использование чего-то готового, такого как решение Ясни в следующем ответе, имеет гораздо больше смысла.
  • 2
    Если ваш пример включает поддержку поддержки netscape, возможно, он не обновлен.
20

Работает для меня:

Update

стиль плагина jQuery:

// 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 );
14

Упрощенный ответ с использованием частей из других ответов, прежде всего user2309766 и dotcomsuperstar.

Особенности:

  • Использует кнопку кнопки Bootstrap для кнопки и поля.
  • Только один вход; несколько входов будут получены формой.
  • Нет дополнительных css, кроме "display: none;" для скрытия ввода файла.
  • Видимая кнопка запускает событие click для скрытого ввода файла.
  • split для удаления пути к файлу используется регулярное выражение и разделители '\' и '/'.

код:

<script src="/bootstrap.min.js"></script>
<link href="/bootstrap.min.css" rel="stylesheet"/>
<script src="/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>
11

С некоторым вдохновением из других сообщений выше, здесь представлено полное решение, которое сочетает в себе то, что выглядит как поле управления формой с добавлением входной группы для чистого виджета ввода файла, который включает ссылку на текущий файл.

.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="/jquery.min.js"></script>
<link rel="stylesheet" href="/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>
8

Это отлично работает для меня

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

Пожалуйста, ознакомьтесь с Twitter файлом загрузки Bootstrap. Он использует очень простое решение, просто добавьте один файл javascript и вставьте следующий код:

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

Простое решение с приемлемым результатом:

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

И стиль:

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

Я создал пользовательскую кнопку загрузки, чтобы принимать только изображения, которые могут быть изменены согласно вашему требованию.

Надеюсь, это поможет!:)

(Используемая структура 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!');
    }
  }
});
3

это лучший стиль загрузки файлов, который мне нравится:

<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

но используя это, вы должны заменить twitter bootstrap на jasny bootstrap files..

С уважением.

2

Решение для множественной загрузки

Я подправил два предыдущих ответа, чтобы включить несколько загрузок. Таким образом, метка показывает имя файла, если выбран только один, или 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>

Изображение 2314

Это может также применяться для изменения текста кнопки и класса.

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

Изображение 2315

2

Я использую http://gregpike.net/demos/bootstrap-file-input/demo.html:

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

или

$('.file-inputs').bootstrapFileInput();
  • 0
    Используйте комментарии для крошечных ответов или предложений.
2

/*  * Bootstrap 3 filestyle  * http://dev.tudosobreweb.com.br/bootstrap-filestyle/  *  * Copyright (c) 2013 Маркус Виниций да Сильва Лима  * Обновление бутстрапа 3 от Paulo Henrique Foxer  * Версия 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);
1

Изображение 2316

Следующий код делает, как показано выше, изображение

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>
1

Я изменил @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>
0

Я подумал, что добавлю свою стоимость в три пенса, просто чтобы сказать, как .custom-file-label BS4 по умолчанию .custom-file-label и custom-file-input input и как это можно использовать.

Последний класс находится в группе ввода и не виден. В то время как первый является видимым ярлыком и имеет псевдоэлемент: 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>

Вы не можете добавлять классы в psuedoelements, но вы можете стилизовать их в CSS (или SASS).

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

В отношении клависного ответа - если вы хотите показать загруженное имя файла в базовой загрузке файла, вы можете сделать это в событии 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>

Этот код JSquery JS отвечает за получение имени загруженного файла:

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

Или с ванильным JS:

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

Изображение 2317

0

Вот альтернативный трюк, это не лучшее решение, но оно просто дает вам выбор

Код 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');
});
0

Новый класс file для кнопки загрузки файла был добавлен в версию BootStrap версии 4-alpha, которая только что была выпущена: http://v4-alpha.getbootstrap.com/components/forms/#file-browser Посетите сайт, чтобы посмотреть, как он выглядит. Вот пример кода для стиля ввода файла с использованием BootStrap 4-alpha:

<label class="file">
  <input type="file" id="file">
  <span class="file-custom"></span>
</label>
0

Попробуйте выполнить в 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>
0

У меня такая же проблема, и я пробую это так.

<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 должна быть в том же теге, что и входной файл

Надеюсь, вы нашли лучшее решение...

0

Никакой фантазии не требуется:

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-selected,.image-file-button,.image-file)

-2

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

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

ИЛИ

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню