Styling file upload button for simple_form_for wit

2019-02-01 06:19发布

Using simple_form_for, Bootstrap and Rails 3. In a form:

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

I don't know how I'd style this so that the "choose file" button can have a different class ('btn btn-primary').

Additionally, when using with Bootstrap at least, its severely misaligned by default. See attached image.

Finally, how do I redefine the text from "No file chosen" to "Chose file" when there isn't one added yet, and show the file name when there is one.

enter image description here

8条回答
Fickle 薄情
2楼-- · 2019-02-01 06:48

Every Browser has a different type of file input field button and this makes it a pain. You can play a little with css. This has given me a basic styling with JS without the annoying "No file chosen" text in chrome and Safary:

$(document).ready(function() {
  $(".your_button").css("width", "80px");
});

Otherwise the best solution is to hide it and show a fake one that intercepts the click:

http://duckranger.com/2012/06/pretty-file-input-field-in-bootstrap/

With respect to the question of how to show that a file has been uploaded, a basic solution with jquery file upload is to detect the upload complete event and replace some of your text with a success message (The exact file name I believe it is not possible to obtain with modern browsers):

$(".your_button").fileupload({
    dataType: "json",
    done: function(e, data) {
        $(".place_for_your_text").text("File uploaded.");
    }
});

In summary, a basic solution is to use javascript in your assets to:

  1. Hide the annoying "No file chosen text" with css.
  2. Place your "Chose file" text next to the button and give it a class you can reference.
  3. Replace the text with "File uploaded"
查看更多
贼婆χ
3楼-- · 2019-02-01 06:51

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>
查看更多
登录 后发表回答