【发布时间】:2018-04-07 11:53:29
【问题描述】:
我正在尝试读取表单上传的 .csv 文件。我的部分答案来自几个答案:In Ruby, how to read data column wise from a CSV file?、how to read a User uploaded file, without saving it to the database 和 Rails - Can't import data from CSV file。但到目前为止,没有任何效果。
这是我的代码:
def upload_file
file = Tempfile.new(params[:search_file])
csv_text = File.read(file)
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
puts row
end
render json: {success: true}
end
我确定该文件不为零。它包含 4 列和 2 行的简单文本。但是,我上面的file 值是一个空数组,而csv_text 值是一个空字符串。我非常确定该文件包含值。
我也试过params[:search_field].read,每次都会抛出一个错误,说“未定义的方法'读取'”。
我怎样才能简单地从用户上传的文件中读取这些值?我在 Rails 5.1.6 和 ruby 2.3 上。
编辑:
我已经尝试了以下一些解决方案。但是,问题是它没有写入文件的 contents,当我调用 file.write 时,它只是将文件名(如 myFileNameHere.csv)写入字符串到临时文件。在下面的代码中,“ok testing now”永远不会打印到终端。这是我现在的代码:
file = Tempfile.new(['hello', '.csv'])
file.write(params[:search_file])
file.rewind
csv_text = file.read
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
puts "ok testing row"
puts row
end
file.close
file.unlink # deletes the temp file
【问题讨论】:
-
我打赌你的 undefined method 'read' 错误信息比你在这里写的要多。请指出整个错误消息,而不仅仅是其中的一部分。我怀疑它说的是没有为
nil对象或类似的东西定义“读取”。检查params[:search_file]的值。可能是nil或不存在的文件。 -
什么是
params[:search_field]? -
嗨@joey,你能告诉我表单中的输入字段吗?
标签: ruby-on-rails ruby