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

nat*_*ate 6 ruby ruby-on-rails

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

# In new.html.erb
<%= file_field_tag 'upload[file]' %>
Run Code Online (Sandbox Code Playgroud)

并访问控制器中的文件

# In controller#create
@text = params[:upload][:file]
Run Code Online (Sandbox Code Playgroud)

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

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

Jos*_*ter 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
Run Code Online (Sandbox Code Playgroud)

形成

意见/联系人/ new_import.html.erb

<%= form_for @contacts, url: import_contacts_path, html: { multipart: true } do |f| %>

  <%= f.file_field :import_file %>

<% end %>
Run Code Online (Sandbox Code Playgroud)

调节器

控制器/ 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
Run Code Online (Sandbox Code Playgroud)

联系型号

车型/ 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
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!

约书亚


suv*_*kar 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 %>
Run Code Online (Sandbox Code Playgroud)

在controller#method_name中

uploaded_file = params[:file]
file_content = uploaded_file.read
puts file_content
Run Code Online (Sandbox Code Playgroud)

在rails中查看更多文件上传http://www.tutorialspoint.com/ruby-on-rails/rails-file-uploading.htm 如何在Ruby中读取整个文件?

希望这会帮助你.

  • 这给了我一个错误:`undefined method'read'for"myfile.txt":String` (3认同)
  • 如果文件上传工作正常,它可以上传任何类型的文件.你错过了'multipart => true'吗?请访问http://www.tutorialspoint.com/ruby-on-rails/rails-file-uploading.htm (2认同)