0

I am trying to upload a file and parse it to rails. I also want to put the content of the file in a sortable table. I followed http://railscasts.com/episodes/396-importing-csv-and-excel?autoplay=true and got through it.

My View file - index.html.erb looks like this -

<%= form_tag import_users_path, multipart: true do %>
Import a file
<%= file_field_tag :file %>
<%= submit_tag "Submit" %>
<% end %>

*_controllers.rb looks like this

class UsersController < ApplicationController
 def index
  @users = User.order(params[:sort])
 end 

 def show
  @user = User.find(params[:id])
 end

 def import
  User.import(params[:file])
  redirect_to action: 'index'
 end
end

Now I want to add styling to the file upload button using Javascript/Bootstrap. I changed the index.html.erb to the following -

<%= form_tag import_users_path, multipart: true do %>
<span class="fileUpload btn btn-primary"> Upload
    <input id="uploadBtn" type="file" class="upload" />
</span>
<%= submit_tag "Submit">
<% end %>

and now assets/javascripts/*.js looks like this -

document.getElementById("uploadBtn").onchange = function() {
document.getElementById("uploadFile").value = this.value;
};

This is not working because the uploaded file is not being parsed as ':file' is not assigned anything.

How can I apply CSS and javascript styling to 'file_field_tag'?

1 Answer 1

1
  1. You should be able to add css styling to the tag the same way you could use for your form helpers as such:

    file_field_tag :file, class: 'whatever-class'

  2. While using your hand-written file input, I think you're not getting a value in your controller because you didn't name your field, fix should be simple as:

    <input id="uploadBtn" type="file" class="upload" name='file' />

  3. I know you can upload file via AJAX/JS but I don't think the process is that straight-forward as I think you'd need to do some custom form serializations using FormData and other stuff like that. Not totally confident that I'm right though!

Sign up to request clarification or add additional context in comments.

1 Comment

I tried it however it did not work. It did not pick my css stylesheet. It doesnot throw any error when I include my css file but it just doesnot apply the css styling defined inside .css

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.