Parsing CSV files sent via form post in Ruby on Rails

I’m not sure why it took me a while to figure this out but it did. The Ruby CSV documentation is really weak and really only explains how to read from a file. I googled around and couldn’t find anyone else talking about how to parse a CSV file sent via a form post (StringIO). I didn’t want to save it to a temp file just so I could follow the CSV docs examples. Here’s what I eventually got to work. Its so short and simple I feel silly for not figuring it out sooner.


parsed_file = CSV::Reader.parse(params[:dump][:file])
parsed_file.each do |row|
p row[0]
end

5 Responses to “Parsing CSV files sent via form post in Ruby on Rails”

  1. vanhowen Says:

    What does your form look like?

    I am having the same problem as you. I have a form to upload a *.csv file, I want to parse that file and input it into my DB. I saw your bits of code, and I am wondering what your form looks like, and how it operates for you to just call parse() on your params like that. My params consist of the path name of the file, or just the filename itself (in firefox), and I do not believe that is correct. Is there anyway you could “spill it out” so to speak ?

  2. vanhowen Says:

    What does your form look like? I do not understand how this works, can you please explain this a little bit further?

  3. vanhowen Says:

    Could you please explain this in more depth. What does your form look like? I am very intrested!

    sincerely,

    Nick

  4. HaPK Says:

    It appears that the form is something like this:

    :import do %>

    Another variant is

    :import do %>
    Paste your CSV file here:

  5. admin Says:

    [source:ruby]

    < %= start_form_tag ({:action=> “import”}, :multipart => true)%>
    File to import: < %= file_field 'dump', 'file' %>
    < %= submit_tag "Import" %>
    < %= end_form_tag %>

    [/source]

    Sorry for the delay.

Leave a Reply

You must be logged in to post a comment.