【发布时间】:2018-05-08 07:51:15
【问题描述】:
在我的视图文件submit.html.erb 中,我决定直接使用<form> 标签,而不是rails 中包含的表单助手。这是视图文件:
<form action = "/winter" method="post">
<input type="file" name="doc">
<p> Upload your question. </p>
<input type = "submit">
<input name="authenticity_token" type="hidden"
value="....">
</form>
提交此表单会在 /winters 上调用带有参数的发布请求
{"doc"=>"1.docx", "authenticity_token"=>"...."}
虽然我预计doc 参数是我上传的文件1.docx,但doc 参数仍然是文件1.docx 的字符串original_filename。
我的routes.rb 文件有代码
post "/winter" => "paper#submit"
而在paper_controller的submit方法里面是代码:
File.write("Papers/rain.docx", params[:doc].read)
redirect_to "/paper"
相应地,当我提交上述表单时,我转到/winters url 并得到错误
“1.docx”的未定义方法“读取”:字符串
那么为什么doc 参数设置为文件名而不是文件本身呢?这与文档相反,我想:[http://guides.rubyonrails.org/form_helpers.html#what-gets-uploaded]
还有一点,可能与此处相关,是在文档的第一段中它说:
根据上传文件的大小,它实际上可能是 StringIO 或由临时文件支持的 File 实例。
那么,是不是说有时params[:doc] 可能是一个文件实例,有时它可能是一个字符串?如何处理这种随机行为?
还有一件事,如果我尝试get 请求而不是put 请求呢? get 必须将参数放在 url 之后,作为查询字符串,对吗?那么params[:doc] 应该始终是一个字符串吗?我尝试使用get,并被发送到url
http://localhost:3000/winter?doc=1.docx
(那时我没有使用 authenticity token 参数的隐藏输入)。
当然也一样
“1.docx”的未定义方法“读取”:字符串
发生错误。
【问题讨论】:
标签: ruby-on-rails forms file-io http-method