在控制器方法中将上传的文件读入File对象 - “无法将Tempfile转换为String”

时间:2010-07-19 02:51:15

标签: ruby-on-rails ruby file file-upload

所以我试图实现文件上传功能,当用户上传文件时,我可以将其读入File对象并相应地处理它:

def create
  name = params[:upload]['datafile'].original_filename
  directory = "public/data"

   # create the file path
   path = File.join(directory, name)

   # read the file
      File.open(params[:upload][:datafile], 'rb') { | file |
         # do something to the file  
    }    
end

当我尝试读取文件时,它会在File.open上抛出“无法将Tempfile转换为字符串”的错误。

我错过了什么?

1 个答案:

答案 0 :(得分:6)

这意味着params[:upload][:datafile]已经是一个文件,因此您无需将其提交给File.open。你的代码应该是:

def create
  name = params[:upload]['datafile'].original_filename
  directory = "public/data"

   # create the file path
   path = File.join(directory, name)

   file = params[:upload][:datafile]
   # do something to the file, for example:
   #    file.read(2) #=> "ab"
end