0

I have a text file of the form

texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
>>>>
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
>>>>
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
etc

and I want to split it along the >>>>'s and save the remainder into Rails Models w/o hacing to save the file on the server. I know that my parser works, but I'm having difficulty figuring out how to parse the file w/o saving it to the server. I've tried calling .read on the params[:file] object, but it throws an exception saying it doesn't have that method. I'd prefer, if possible, to avoid paperclip and carrierwave. Could anyone give some sample code on how to access the text w/o having to save it?

EDIT: The code I have tried comes from this stack exchange question How to upload a text file and parse contents into database in RoR

uploaded_io = params[:file_upload]
file_contents = uploaded_io.read
file_contents.each_line do |f|
...
end
Community
  • 1
  • 1
Simon Means
  • 230
  • 3
  • 11

2 Answers2

1

When you upload a file, Rails will create a file in the tmp directory, which will later be deleted automatically. Therefore, you don't have to do anything for the upload to be automatically deleted. That means that if you wanted to keep the file, you would need to copy it manually to a permanent location.

You can access the temporary file by calling the tempfile method on params[:file_upload], for example:

class UploadController < ApplicationController
  def new
    # upload form
  end

  def create
    data = params[:file_upload].tempfile.read
    parts = data.split(">>>>\n")

    # do something with parts
  end
end
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
0
file_io = params[:file]
stream = file_io.read 

Should work, but make sure your form is setup correctly, and that your calling the correct params object. Also try adding multipart: true to your form options. I've had similar problems to this before, and it was actually that the file upload wasn't being used properly.

You can inspect params[:file] for file_io.original_filename too - even if your read isnt working, you should still be able to access the filename. If that doesnt work either, the problem is most likely something else (probably the form builder).

Ash
  • 24,276
  • 34
  • 107
  • 152