6

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

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

并访问控制器中的文件

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

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

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

4

2 回答 2

8

完整示例

例如,上传包含联系人的导入文件。您无需存储此导入文件,只需对其进行处理并丢弃即可。

路线

路线.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

希望有帮助!

约书亚

于 2015-07-03T15:39:02.843 回答
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 %>

在控制器#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 如何在 Ruby 中读取整个文件?

希望这会帮助你。

于 2012-05-03T07:33:35.187 回答