如何阅读上传的文件

时间:2014-08-22 09:28:37

标签: ruby-on-rails ruby

我正在给用户上传文件的机会。但是,应用程序不会将这些文件保存到数据库中,只需要从中获取信息。

所以从一个看起来像这样的形式:

= simple_form_for @channel, method: :post do |f|
    = f.input :name
    = f.input :configuration_file, as: :file
    = f.submit

params[:channel][:configuration_file]

#<ActionDispatch::Http::UploadedFile:0xc2af27c @original_filename="485.csv", @content_type="text/csv", @headers="Content-Disposition: form-data; name=\"channel[configuration_file]\"; filename=\"485.csv\"\r\nContent-Type: text/csv\r\n", @tempfile=#<File:/tmp/RackMultipart20140822-6972-19sqxq2>>

我怎样才能从这件事中读到什么?我试过了

File.open(params[:channel][:configuration_file])

但它返回错误

!! #<TypeError: can't convert ActionDispatch::Http::UploadedFile into String>

PS xml和csv的其他解决方案将非常感谢!

2 个答案:

答案 0 :(得分:2)

根据Rails文档:

http://api.rubyonrails.org/classes/ActionDispatch/Http/UploadedFile.html

上传的文件支持以下实例方法,其中包括:

open() 

path()

read(length=nil, buffer=nil) 
你可以尝试:

my_data = params[:channel][:configuration_file].read

获取文件内容的字符串?

甚至:

my_data = File.read params[:channel][:configuration_file].path

此外,如果文件可能很长,您可能想要打开文件并逐行读取。这里有一些解决方案:

How to read lines of a file in Ruby

如果您想阅读CSV文件,可以尝试:

require 'csv'    

CSV.foreach(params[:channel][:configuration_file].path, :headers => true) do |row|
  row_hash = row.to_hash
  # Do something with the CSV data
end

假设您的CSV中有标题。

对于XML,我推荐优秀的Nokogiri宝石:

http://nokogiri.org/

至少部分是因为它使用高效的C库来导航XML。 (如果你使用JRuby,这可能是个问题)。它的使用可能超出了这个答案的范围,并在Nokogiri文档中得到了充分的解释。

答案 1 :(得分:0)

来自documentation

  

实际文件可通过tempfile访问器访问,但有些文件可以访问   其界面直接方便使用。

您可以将代码更改为:

file_content = params[:channel][:configuration_file].read

或者如果您想使用文件API:

file_content = File.read params[:channel][:configuration_file].path
相关问题