ruby-on-rails – 如何在RoR中上传文本文件并将内容解析到数据库
发布时间:2020-12-16 22:36:36 所属栏目:百科 来源:网络整理
导读:到目前为止,我已设法上传文件: # In new.html.erb%= file_field_tag 'upload[file]' % 并访问控制器中的文件 # In controller#create@text = params[:upload][:file] 但是,这只给出了文件名,而不是文件的内容.我如何访问其内容? 我知道这是一个跳转,但是一
到目前为止,我已设法上传文件:
# In new.html.erb <%= file_field_tag 'upload[file]' %> 并访问控制器中的文件 # In controller#create @text = params[:upload][:file] 但是,这只给出了文件名,而不是文件的内容.我如何访问其内容? 我知道这是一个跳转,但是一旦我可以访问文件的内容,是否可以上传文件夹并遍历文件? 解决方法
完整的例子
例如,上传包含联系人的导入文件.您不需要存储此导入文件,只需处理它并将其丢弃即可. 路线 的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 希望有所帮助! 约书亚 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |