Ruby on rails 在Rails中上载文件时会给出字符串文件名,而不是文件或StringIO对象

Ruby on rails 在Rails中上载文件时会给出字符串文件名,而不是文件或StringIO对象,ruby-on-rails,forms,file-upload,Ruby On Rails,Forms,File Upload,Rails 3,JRuby 1.6.7.2 我一直在尝试一些“基本”的东西,只是通过一个表单上传一个文本文件,以便在我的应用程序中处理。我看到的问题是,我得到的不是StringIO或文件,而是文件名的字符串 def file @upload = params[:upload][:file] render :template => 'api/file.html.haml' end 这是表格代码 = form_tag(:controller =&g

Rails 3,JRuby 1.6.7.2

我一直在尝试一些“基本”的东西,只是通过一个表单上传一个文本文件,以便在我的应用程序中处理。我看到的问题是,我得到的不是StringIO或文件,而是文件名的字符串

def file
        @upload = params[:upload][:file]
        render :template => 'api/file.html.haml'
      end
这是表格代码

= form_tag(:controller => "api/#{CURRENT_API_VERSION}/api", :action => 'file', :method=> :post, :multipart => true) do
    = label_tag "file"
    = file_field_tag "upload[file]"
    = submit_tag 'Analyze!'
以及控制器代码,它只是将@upload作为包含文件名的字符串提供给我

def file
        @upload = params[:upload][:file]
        render :template => 'api/file.html.haml'
      end

在控制器中运行调试器会给我@upload.class=String,它不会响应任何文件或StringIO方法,例如read

在这里找到了答案。原来我只是把form_tag方法调用搞砸了。您需要将“url_for”的选项与其他选项分开,特别是多部分选项

因此,表单的正确代码为:

= form_tag({:controller => "api/#{CURRENT_API_VERSION}/api", :action => 'file', :method=> :post}, {:multipart => true}) do
    = label_tag "file"
    = file_field_tag "upload[file]"
    = submit_tag 'Analyze!'
感谢Rob Biedenharn五年前在ruby论坛上回答这个问题!

form_标记({:controller=>“api/{CURRENT\u api\u VERSION}/api”,:action=>“file',:method=>:post},:multipart=>true)相同。