我是Rails的新手。 在我的用户必须上传文件的项目中,我将其存储起来 然后我必须解析文件内容并以新的形式显示它。
我已成功完成文件上传部分, 现在我应该如何阅读它的内容?
答案 0 :(得分:5)
尝试这样的事情:
upload = params[:your_upload_form_element]
content = upload.is_a?(StringIO) ? upload.read : File.read(upload.local_path)
非常小的文件可以作为字符串而不是上传的文件传递,因此您应该检查并相应地处理它。
答案 1 :(得分:2)
您可以使用File类在Ruby中打开文件并阅读其内容,如下面的简单示例所示:
# 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
答案 2 :(得分:0)
例如,上传包含联系人的导入文件。您不需要存储此导入文件,只需处理它并丢弃它。
<强>的routes.rb 强>
resources :contacts do
collection do
get 'import/new', to: :new_import # import_new_contacts_path
post :import, on: :collection # import_contacts_path
end
end
<强>视图/联系人/ new_import.html.erb 强>
<%= form_for @contacts, url: import_contacts_path, html: { multipart: true } do |f| %>
<%= f.file_field :import_file %>
<% end %>
<强>控制器/ contacts_controller.rb 强>
def new_import
end
def import
begin
Contact.import( params[:contacts][:import_file] )
flash[:success] = "<strong>Contacts Imported!</strong>"
redirect_to contacts_path
rescue => exception
flash[:error] = "There was a problem importing that contacts file.<br>
<strong>#{exception.message}</strong><br>"
redirect_to import_new_contacts_path
end
end
<强>模型/ contact.rb 强>
def import import_file
File.foreach( import_file.path ).with_index do |line, index|
# Process each line.
# For any errors just raise an error with a message like this:
# raise "There is a duplicate in row #{index + 1}."
# And your controller will redirect the user and show a flash message.
end
end
希望能帮助别人!
JP