【问题标题】:Uploading file in Rails gives String filename instead of File or StringIO object在 Rails 中上传文件给出 String 文件名而不是 File 或 StringIO 对象
【发布时间】:2012-08-07 09:52:16
【问题描述】:

Rails 3,JRuby 1.6.7.2

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

这是表单代码

= 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方法,例如读取。

【问题讨论】:

    标签: ruby-on-rails forms file-upload


    【解决方案1】:

    在这里找到答案。原来我只是搞砸了 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​​-forum 上回答这个问题! http://www.ruby-forum.com/topic/125637

    【讨论】:

    • form_tag({:controller => "api/#{CURRENT_API_VERSION}/api", :action => 'file', :method=> :post}, :multipart => true)
    猜你喜欢
    • 1970-01-01
    • 2015-10-03
    • 2014-03-18
    • 2013-07-09
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    相关资源
    最近更新 更多