如何上传文本文件并将内容解析到 RoR 中的数据库中 [英] How to upload a text file and parse contents into database in RoR

查看:39
本文介绍了如何上传文本文件并将内容解析到 RoR 中的数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经成功上传了一个文件:

So far I've managed to upload a file:

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

并访问控制器中的文件

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

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

However, this gives me just the filename, not the file's contents. How do I access its contents?

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

I know this a jump, but once I can access the file's contents, would it all be possible to upload a folder and iterate through the files?

推荐答案

完整示例

以上传包含联系人的导入文件为例.您不需要存储这个导入文件,只需处理它并丢弃它.

Complete Example

Take, for example, uploading an import file containing contacts. You don't need to store this import file, just process it and discard it.

routes.rb

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

    post :import                       # import_contacts_path
  end
end

表格

views/contacts/new_import.html.erb

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

  <%= f.file_field :import_file %>

<% end %>

控制器

controllers/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

联系方式

models/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

希望有帮助!

约书亚

这篇关于如何上传文本文件并将内容解析到 RoR 中的数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆