读入文件内容栏 [英] Reading in file contents rails
本文介绍了读入文件内容栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个试图读取JSON文件以进行解析/动作/等的表单.我在将其读取到控制器中时遇到问题.
I have a form that is attempting to read in a JSON file for parsing/actions/etc. I'm having problems getting it to read in the controller.
查看:
<%= form_tag({:controller => :admins, :action => :upload_json}, {:multipart => true, :method => :post}) do |f| %>
<%= file_field_tag 'datafile' %>
<%= submit_tag "Upload" %>
控制器:
def upload_json
file_data = params[:datafile]
File.read(file_data) do |file|
file.each do |line|
## does stuff here....
end
end
end
当我为数据添加种子时,我的seed.rb
文件中也可以使用类似的功能-只是无法读取上传的文件中的数据.
A similar function works in my seed.rb
file when I'm seeding data - just can't get it to read in an uploaded file.
我遇到的错误是:can't convert ActionDispatch::Http::UploadedFile into String
.
提前感谢您的帮助!
推荐答案
弄清楚了.需要更改:
file_data = params[:datafile]
到
file_data = params[:datafile].tempfile
并决定使用.open
函数进行更改:
And decided to use the .open
function to change:
File.read(file_data) do |file|
到
File.open(file_data, 'r') do |file|
这篇关于读入文件内容栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文