BrandoN
BrandoN

Reputation: 313

Pass Uploaded File path To File.read(path)

image

As you can see from the picture, i have a button to upload a csv file. How can i get the uploaded file to file.read(PATH) so the script takes the file in.

My Controller (calls_controller.rb)

  def index

    csv_text = File.read(UPLOADED FILE PATH)
    csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1', :col_sep => ',')
  ...
  ..
  end

I tried to give my index method an argument

  def index(file)

but that did not work for me.

This is my view (index.html.erb). I call out the method in the submit_tag, but can i somehow pass an argument or ?.

<div>
  <h4>Import data!</h4>
  <%= form_tag import_calls_path, multipart: true do  %>
    <%= file_field_tag :file, required: true %>
    <%= submit_tag "Import CSV", method: :index%>
  <% end %>

</div>

Upvotes: 2

Views: 1082

Answers (1)

spickermann
spickermann

Reputation: 106792

When you upload a file with a form like the one in your question then the following should work:

File.read(params[:file].tempfile.path)

Or even simpler:

params[:file].read

Upvotes: 3

Related Questions