Reputation: 389
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'?
Upvotes: 0
Views: 1118
Reputation: 5633
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'
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' />
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!
Upvotes: 1