我在nil上获得了未定义的方法`name':简单文件上传表单上的NilClass。
查看
<%= form_tag({action: :upload}, multipart: true) do %>
<%= file_field_tag 'picture' %>
<%= submit_tag "Upload & Produce Result" %>
<% end %>
控制器
def upload
file_name = params['picture']
if file_name[-4,4] != ".txt"
respond_to do |format|
flash[:notice] = "Please upload only txt file"
format.html { redirect_to :action => :index }
end
end
File.open(Rails.root.join('public', 'uploads', file_name.original_filename), 'w') do |file|
file.write(file_name.read)
end
end
路线
root :to => 'home#index'
post 'upload', to: 'home#upload'
发布参数
{"utf8"=>"✓",
"authenticity_token"=>"HPM76LFj/3Pt7ur1EfMz4SR5T8A9gvoe+JRmneHbu5c=",
"picture"=>#<ActionDispatch::Http::UploadedFile:0x007f7418370210 @tempfile=# <Tempfile:/tmp/RackMultipart20130907-9689-viscwz>,
@original_filename="data.txt",
@content_type="text/plain",
@headers="Content-Disposition: form-data; name=\"picture\"; filename=\"data.txt\"\r\nContent-Type: text/plain\r\n">,
"commit"=>"Upload & Produce Result"}
即使我尝试了
raise params.to_yaml
它给出了同样的错误。
任何帮助都将不胜感激。
感谢。
答案 0 :(得分:2)
你正在考虑将params ['picture']作为字符串,而你给出的Post参数显示params ['picture']是'ActionDispatch :: Http :: UploadedFile'对象
所以,您可以尝试用
替换params ['picture']params[:picture].original_filename
您还可以获取文件上传的其余部分:params [:picture] .tempfile,params [:picture] .headers,params [:picture] .content_type
您也可以使用类似问题Reading in file contents rails
来引用这篇文章