使用Rails 3中的Bootstrap为simple_form_for设置样式文件上传按钮

tib*_*bon 13 file-upload ruby-on-rails simple-form twitter-bootstrap

使用simple_form_for,Bootstrap和Rails 3.在一个表单中:

<%= f.input :upload, label: 'PDF file:' , input_html: {accept: ('application/pdf') } %>

我不知道我如何设置这个样式,以便"选择文件"按钮可以有不同的类('btn btn-primary').

此外,至少在使用Bootstrap时,默认情况下严重错位.见附图.

最后,当没有添加文本时,如何将文本从"未选择文件"重新定义为"选择文件",并在有文件名时显示文件名.

在此输入图像描述

BSB*_*BSB 23

我是这样做的:

  1. 在视图中添加表单文件字段并将其隐藏
  2. 添加样式化的附加字段只是为了显示文件名
  3. 添加按钮以触发文件浏览对话框

    <div class="control-group">
      <div class="attach-set">
        <%= f.input :real_file, input_html: { hidden: true }, label: 'Upload Attachment' %>
        <div class="input-append">
          <input id="file-display" class="input-large uneditable-input" type="text">
          <a id="upload-btn" class="btn"><i class="icon-upload-alt"></i> Browse</a>
        </div>
      </div> <!-- /attach-set -->
    </div> <!-- /control-group -->
    
    Run Code Online (Sandbox Code Playgroud)
  4. 在您的JS(显示的咖啡与jQuery)中,将显示按钮上的单击传递到真实文件输入,当他们选择文件时,在显示文本字段中删除文件名(我删除路径以便我看不到C:\ FakePath ....)

    $(document).ready ->
    
      # ------------------------------------------------------
      # pretty-fy the upload field
      # ------------------------------------------------------
      $realInputField = $('#real_file')
    
      # drop just the filename in the display field
      $realInputField.change ->
        $('#file-display').val $(@).val().replace(/^.*[\\\/]/, '')
    
      # trigger the real input field click to bring up the file selection dialog
      $('#upload-btn').click ->
        $realInputField.click()
    
    Run Code Online (Sandbox Code Playgroud)


Yok*_*oko 11

这对我很有用,只需要HTML

<label class="btn btn-primary">
  Add a file!
  <span style="display:none;">
    <%= f.file_field :image, required: true, multiple: true, name: 'picture' %>
  </span>
</label>
Run Code Online (Sandbox Code Playgroud)


kro*_*oss 6

我跑过去,正在使用Jasny扩展到Bootstrap 3.到目前为止它似乎运作良好.