Re: Handling File on Upload

David Kahn
2010-12-06T03:21:49Z

On Sun, Dec 5, 2010 at 8:54 PM, spncrgr
<thisbudsforyou1-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:

> Hello,
>
> I need some help trying to figure out how to add the ability for a
> user to upload a text file, and then have the application parse that
> text file, and add each record as instance of a model object.
I''ve
> found a lot of helpful articles out there, but I''m stuck trying to
> bring it all together since I''m still very new to all of this.
>
> Here''s my view code:
> # index.html.erb
> <% form_for :upload, :url => { :action => :upload }, :html =>
> { :multipart => true } do |f| %>
>
> Please select a file to upload:
>    <%= f.file_field :file %>
>    <%= f.submit ''Upload'', :disable_with =>
"Uploading..." %>
>
> <% end %>
>
> In my controller, I''ve been able to write something like this to
work
> with the data in my upload view:
>
> # mailing_lists_controller.rb
> def upload
>    file = params[:upload][:file]
>    @data = file.read
>

So here you probably want to read the file line by line and then do your
magic on each line to create the model record for the line. You may have to
play with it - not sure if you are going to need to save the file in a temp
location first to do this. I dealt with a similar issue and file.read on the
uploaded file parameter gives you a string, not a file object and you want a
file object if you want to read it line by line:

file = File.new(params[:upload][:file]   # maybe you can do this... have to
try... if not you may just need to save it to a temp location,
                                                           #  perhaps
someone else has a better idea (also check params[:upload][:file] for its
class... if the
                                                           # class is File
then you are set.
while(line=file.gets)
   m = Model.new
   # do your magic here
   m.save
end
file.close


 end
>
> so then the view looks like this:
> # upload.html.erb
> <% @data.split("\r\n").each do |row| %>
>
>    <%= row.split("\t").join(" | ") %>
>
> <% end %>
>
>
> So, where I''m stuck is translating that into saving each row as a
> record in the database.  I''ve tried several different things in
the
> model (like creating a "process" method or using
"before_save"), but
> nothing has been successful thus far (probably because I''m not
> implementing it correctly).
>
> Any help would be appreciated.
>
> Thanks,
> Spencer
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Talk" group.
> To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
> To unsubscribe from this group, send email to
>
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org<rubyonrails-talk%2Bunsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org>
> .
> For more options, visit this group at
> http://groups.google.com/group/rubyonrails-talk?hl=en.