如何在RoR中上传文本文件并将内容解析到数据库中

时间:2012-05-03 06:19:58

标签: ruby-on-rails ruby

到目前为止,我已设法上传文件:

# In new.html.erb
<%= file_field_tag 'upload[file]' %>

并访问控制器中的文件

# In controller#create
@text = params[:upload][:file]

但是,这只给出了文件名,而不是文件的内容。我如何访问其内容?

我知道这是一个跳转,但是一旦我可以访问文件的内容,是否可以上传文件夹并遍历文件?

2 个答案:

答案 0 :(得分:8)

完整示例

例如,上传包含联系人的导入文件。您不需要存储此导入文件,只需处理它并丢弃它。

路线

<强>的routes.rb

resources :contacts do 
  collection do
    get 'import/new', to: :new_import  # import_new_contacts_path

    post :import                       # 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

希望有所帮助!

约书亚

答案 1 :(得分:5)

在new.html.erb

<%= form_tag '/controller/method_name', :multipart => true do %>
   <label for="file">Upload text File</label> <%= file_field_tag "file" %>
   <%= submit_tag %>
<% end %>

在controller#method_name

uploaded_file = params[:file]
file_content = uploaded_file.read
puts file_content

在rails http://www.tutorialspoint.com/ruby-on-rails/rails-file-uploading.htm中查看有关文件上传的详情  How to read whole file in Ruby?

希望这会对你有所帮助。