I am new to Rails. In my project where users have to upload a file, I store it then I have to parse the file contents and show it in new form.
I have successfully done the file uploading portion, now how should I read the contents of it?
I am new to Rails. In my project where users have to upload a file, I store it then I have to parse the file contents and show it in new form.
I have successfully done the file uploading portion, now how should I read the contents of it?
You can open files and read their contents in Ruby using the File class, as this simple example demonstrates:
# Open a file in read-only mode and print each line to the console
file = File.open('afile.txt', 'r') do |f|
f.each do |line|
puts line
end
end
Try something like this:
upload = params[:your_upload_form_element]
content = upload.is_a?(StringIO) ? upload.read : File.read(upload.local_path)
Very small files can be passed as strings instead of uploaded files, therefore you should check for that and handle it accordingly.