max_ max_ - 1 year ago 121
Ruby Question

Uploading a file in Rails

I'm new to rails, and I'm writing a RESTful website using the CRUD technique. So far I have created three pages, all of which allow the user to create, edit, and delete a row from the database. However, my fourth page will need to include an upload file form, but a) I don't know how the filesystem works with Rails thus I don't know where files should be stored. The file would be around 100kb and couldn't be stored in temporary storage because it will be constantly downloaded. And b) I don't know how to write to a file.

It would be great if you could tell me how to do what I mentioned above - create an upload input on an input form, and to then write the file to a filepath in a separate directory.

Answer Source

While there are plenty of gems that solve file uploading pretty nicely (see for a list), rails has built-in helpers which make it easy to roll your own solution.

Use the file_field-form helper in your form, and rails handles the uploading for you:

<%= form_for @person do |f| %>
  <%= f.file_field :picture %>
<% end %>

You will have access in the controller to the uploaded file as follows:

uploaded_io = params[:person][:picture]'public', 'uploads', uploaded_io.original_filename), 'wb') do |file|

It depends on the complexity of what you want to achieve, but this is totally sufficient for easy file uploading/downloading tasks. This example is taken from the rails guides, you can go there for further information:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download