I am referring to the stackoverflow post https://stackoverflow.com/a/2521135/2607331
to understand how to read files.
View -
<%= form_tag ('/greetings/hello') do %>
<label for="file">File to Upload</label> <%= file_field_tag "file" %>
<div><%= submit_tag 'Process' %></div>
<% end %>
Routes -
Rails.application.routes.draw do
post 'greetings/hello'
controller -
class GreetingsController < ApplicationController
def hello
@filename = params[:file]
if @filename.respond_to?(:read)
@lines = file_data.read
elsif @filename.respond_to?(:path)
@lines = File.read(file_data.path)
else
logger.error "Bad file_data: #{@filename.class.name}: #
{@filename.inspect}"
end
render "hello"
end
end
As per the post, the params[:file] would be a tempfile or StringIO object, however in my case it is string. Not sure what is going wrong. Below is the logger output.
Started POST "/greetings/hello" for 183.83.51.8 at 2016-05-03 03:45:40 +0000
Cannot render console from 183.83.51.8! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by GreetingsController#hello as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"0r0Ny6rqlv9Gts1PBh+J4Dk7B+9WPea3HK1cgR/dWTLFrkXW+eggX+tie4wFs+F4lHM5RGpAHXL6EO3sKjd0sw==", "file"=>"sitcomquery.txt", "commit"=>"Process"}
Bad file_data: String: "sitcomquery.txt"
Rendered greetings/hello.html.erb within layouts/application (5.6ms)
Completed 500 Internal Server Error in 97ms (ActiveRecord: 0.0ms)
EDIT
Changed index.html.erb to include multipart -
<%= form_tag '/greetings/hello' ,multipart: true do %>
<label for="file">File to Upload</label> <%= file_field_tag "file" %>
<div><%= submit_tag 'Process' %></div>
<% end %>
In controller, I am able to read it with -
tempfl = params[:file]
@lines = tempfl.read
However, @lines is a big string. I need to read it in such a way that @lines is array of lines. However readlines is not a method of ActionDispatch::Http::UploadedFile object. Do i need to save the file and perform readlines, or is there anyway I can read each line without saving file.