Reading in file contents rails

2020-06-16 04:28发布

I have a form that is attempting to read in a JSON file for parsing/actions/etc. I'm having problems getting it to read in the controller.

View:

<%= form_tag({:controller => :admins, :action => :upload_json}, {:multipart => true, :method => :post}) do |f| %>

    <%= file_field_tag 'datafile' %>

<%= submit_tag "Upload" %>

Controller:

def upload_json

  file_data = params[:datafile]

  File.read(file_data) do |file|

     file.each do |line|
       ## does stuff here....
     end
  end

end

A similar function works in my seed.rb file when I'm seeding data - just can't get it to read in an uploaded file.

The error I'm getting is: can't convert ActionDispatch::Http::UploadedFile into String.

Thanks in advance for the help!

3条回答
成全新的幸福
2楼-- · 2020-06-16 05:07

Figured it out. Needed to change:

file_data = params[:datafile]

to

file_data = params[:datafile].tempfile

And decided to use the .open function to change:

File.read(file_data) do |file|

to

File.open(file_data, 'r') do |file|  
查看更多
▲ chillily
3楼-- · 2020-06-16 05:08

Open the uploaded file using path.

params[:datafile] is an instance of ActionDispatch::Http::UploadedFile class and you'll need to get at the stored file by calling path to properly process it.

Additionally, File.read will not get you the line-by-line processing you're looking for. You need to change that to File.open.

Try this:

Controller

def upload_json

  uploaded_datafile = params[:datafile]

  File.open( uploaded_datafile.path ) do |file|

     file.each_line do |line|

       # Do something with each line.

     end

  end

end

Alternative Style

def upload_json

  File.foreach( params[:datafile].path ) do |line|

    # Do something with each line.

  end 

  # FYI: The above method block returns `nil` when everything goes okay.

end
查看更多
对你真心纯属浪费
4楼-- · 2020-06-16 05:17

params[:datafile] is an instance of ActionDispatch::Http::UploadedFile class with tempfile attached with that.To open the tempfile

You try something like

File.open(params[:datafile].path) do |file|
 #your stuff goes here
end
查看更多
登录 后发表回答