Styling file upload button for simple_form_for with Bootstrap in Rails 3

Solution 1:

This is how I do it:

  1. In the view add your form file field and hide it
  2. Add a styled additional field just to display the file name
  3. Add a button to trigger the file browse dialog

    <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 -->
    
  4. In your JS (Coffee w/ jQuery shown), pass the click from the display button onto the real file input and when they select a file drop the file name in the display text field (I drop the path so that I don't see 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()
    

Solution 2:

This worked great for me and only requires 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>

Solution 3:

I ran across and am using Jasny's extension to Bootstrap 3. It seems to work well so far.

Solution 4:

No JS required, just plain css

scss

.fileinput-button {
  position: relative;
  overflow: hidden;
  float: left;
  margin-right: 4px;
  width: 110px;
  height: 32px;
  input{
    opacity: 0;
    filter: alpha(opacity=0);
    transform: translate(-300px, 0) scale(4);
    direction: ltr;
    cursor: pointer;
  } 
}

html / slim

span class="btn btn-success fileinput-button"
  i.fa.fa-pencil
  span
   |  Select File
  = f.file_field :cover_ar

I recommend using compass for cross browser compatibility