当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - Custom Resource Routes and Uploading

问题描述:

I have read and followed many different questions and forums on this topic but something is not right. I am trying to do a simple image upload. I have in my view:

<div class="row">

<div class="col-sm-6">

<%= form_tag("/beers/newCal", method: "get", multipart: true) do %>

<%= label_tag(:q, "Enter date (dd/mm): ") %>

<%= text_field_tag(:date) %>

<br/>

<%= label_tag(:q, "Enter event name: ") %>

<%= text_field_tag(:event) %>

<br/>

<%= submit_tag("Create Calendar Event") %>

<br /> <br />

<% end %>

<%= form_tag("/beers/upload", multipart: true) do %>

<%= file_field_tag 'picture' %>

<% end %>

</div>

and in my controller

def upload

uploaded_io = params[:picture]

File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|

file.write(uploaded_io.read)

end

end

I am able to select the image for upload but it is not saving in the #{Rails.root}/public/uploads directory. The file name is not written or anything. When I comment out the upload function definition I do not get an error (which I expected to).

In my routes file I have tried

get 'beers/upload'

and

resources :beers

I have tried plenty of different combinations but this is the most basic way I have seen this done.

I am using ruby version 2.1.5p273 and rails version 4.1.8 on Amazon Ubuntu EC2. Please tell what I am doing wrong.

网友答案:

You have no submit button in your second form - how do you submit it? Just selecting a file will not submit it.

Further your action should be a post request, try

post 'beers/upload', to: 'beers#upload'

or even more dogmatic

resources :beers do
  collection do
    post :upload
  end
end
分享给朋友:
您可能感兴趣的文章:
随机阅读: