如何通过表单获取临时文件的内容

时间:2013-05-20 11:12:41

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2

index.html.erb

= form_for :file_upload, :html => {:multipart => true} do |f|
      = f.label :uploaded_file, 'Upload your file.'
      = f.file_field :uploaded_file
      = f.submit "Load new dictionary"

模型

def file_upload
    file = Tempfile.new(params[:uploaded_file])
    begin
        @contents = file
    ensure
        file.close
        file.unlink   # deletes the temp file
    end
end

索引

def index
    @contents
end

但上传文件= @contents

后,我的页面中没有打印任何内容

2 个答案:

答案 0 :(得分:5)

使用file.read阅读上传文件的内容:

def file_upload
  @contents = params[:uploaded_file].read
  # save content somewhere
end

答案 1 :(得分:0)

解决问题的一种方法是将file_upload定义为类方法,并在控制器中调用该方法。

index.html.erb

= form_for :index, :html => {:multipart => true} do |f|
      = f.label :uploaded_file, 'Upload your file.'
      = f.file_field :uploaded_file
      = f.submit "Load new dictionary"

模型

def self.file_upload uploaded_file
  begin  
    file = Tempfile.new(uploaded_file, '/some/other/path')        
    returning File.open(file.path, "w") do |f|
      f.write file.read
      f.close
    end        
  ensure
    file.close
    file.unlink   # deletes the temp file
  end

end

控制器

def index
  if request.post?  
    @contents = Model.file_upload(params[:uploaded_file])
  end
end

您需要进行健全性检查和处理。现在,在Controller中定义了@contents,您可以在View中使用它。