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

ahm*_*met 8 ruby ruby-on-rails 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"
Run Code Online (Sandbox Code Playgroud)

模型

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

指数

def index
    @contents
end
Run Code Online (Sandbox Code Playgroud)

但是在上传文件后,我的页面中没有任何内容被打印出来 = @contents

aro*_*ero 7

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

def file_upload
  @contents = params[:uploaded_file].read
  # save content somewhere
end
Run Code Online (Sandbox Code Playgroud)