8

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

4

2 回答 2

7

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

def file_upload
  @contents = params[:uploaded_file].read
  # save content somewhere
end
于 2013-05-20T12:24:50.883 回答
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

你需要应用健全性检查和其他东西。现在它@contents在 Controller 中定义,您可以在 View 中使用它。

于 2013-05-20T13:29:46.607 回答