【问题标题】:How do I get the contents of temp file through a form如何通过表单获取临时文件的内容
【发布时间】:2013-05-20 11:12:41
【问题描述】:

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后,我的页面上没有打印任何内容

【问题讨论】:

  • 你是如何将params[:uploaded_file] 加入你的模型的?看起来像控制器代码

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


【解决方案1】:

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

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

【讨论】:

  • 如何将内容发送回索引
【解决方案2】:

解决此问题的一种方法是将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中使用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 2016-04-06
    • 2011-04-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多