【问题标题】:Reading in file contents rails读入文件内容 rails
【发布时间】:2012-09-25 19:43:17
【问题描述】:

我有一个表单正在尝试读取 JSON 文件以进行解析/操作/等。我无法让它在控制器中读取。

查看:

<%= 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 文件中也有类似的功能 - 只是无法让它在上传的文件中读取。

我得到的错误是:can't convert ActionDispatch::Http::UploadedFile into String

提前感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 json


    【解决方案1】:

    想通了。需要更改:

    file_data = params[:datafile]
    

    file_data = params[:datafile].tempfile
    

    并决定使用.open函数进行更改:

    File.read(file_data) do |file|
    

    File.open(file_data, 'r') do |file|  
    

    【讨论】:

    • 为了清楚起见,解决 can't convert ActionDispatch::Http::UploadedFile into String 错误的是 .tempfile 方法(不是对 File.open 的更改)。
    • @Mike 为了更清楚起见,使用File.read 不会得到你想要的逐行处理。使用File.open
    【解决方案2】:

    params[:datafile] 是 ActionDispatch::Http::UploadedFile 类的一个实例,带有附加的临时文件。打开临时文件

    你可以试试

    File.open(params[:datafile].path) do |file|
     #your stuff goes here
    end
    

    【讨论】:

      【解决方案3】:

      使用path打开上传的文件。

      params[:datafile]ActionDispatch::Http::UploadedFile 类的一个实例,您需要通过调用path 来获取存储的文件以正确处理它。

      此外,File.read 不会为您提供所需的逐行处理。您需要将其更改为 File.open

      试试这个:

      控制器

      def upload_json
      
        uploaded_datafile = params[:datafile]
      
        File.open( uploaded_datafile.path ) do |file|
      
           file.each_line do |line|
      
             # Do something with each line.
      
           end
      
        end
      
      end
      

      另类风格

      def upload_json
      
        File.foreach( params[:datafile].path ) do |line|
      
          # Do something with each line.
      
        end 
      
        # FYI: The above method block returns `nil` when everything goes okay.
      
      end
      

      【讨论】:

        猜你喜欢
        • 2011-03-04
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多