在Rails中读取上传的JSON文件

时间:2015-08-19 11:12:12

标签: ruby-on-rails ruby

我在Rails中上传一个JSON文件,以便解析它然后插入数据库而不存储文件本身

表格

= form_tag import_posts_path do
  = file_field_tag :file
  = submit_tag "import"

控制器方法

def import
  file = params[:file]

  puts "file => " + file # file => posts.json

  data = File.read(params[:file]) # Errno::ENOENT at /posts/import No such file or directory @ rb_sysopen - posts.json

  json = JSON.parse(data)
end

路由

resources :posts do
  collection { post :import }
end

终端中的请求信息,posts.json就在那里,但我得到了Errno::ENOENT at /posts/import No such file or directory @ rb_sysopen - posts.json

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"9lzpwyCWclgiI4WA/zho5y1WLCBQtRL7z3FcAn+wc80=", "file"=>"posts.json", "commit"=>"import"}
file => posts.json
Completed 500 Internal Server Error in 23ms

1 个答案:

答案 0 :(得分:1)

解决方案:

更新表单以将文件作为多部分表单数据发送为@usmanali建议

= form_tag import_posts_path, multipart: true do
  = file_field_tag :file
  = submit_tag "import"

然后在控制器中read直接进入params[:file],如answer

所述
def import
  file = params[:file].read
  data = JSON.parse(file)
end