Reputation: 2249
I've tried to find the documentation file handling in Rails, without success. Here's the link to the File class (specified by the docs for file_filed_tag): http://api.rubyonrails.org/classes/File.html
I figure there's got to be a better set of source docs. My main question is about where can I save a file that is not publicly accessible. I'm interested in using file uploaded files temporarily for "wizard" like purposes for users.
Upvotes: 4
Views: 5983
Reputation: 10070
The Rails documentation only mentions this in passing The source that handles uploads is https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/http/upload.rb
You could use the gem "paperclip" to handle the file upload for you:
https://github.com/thoughtbot/paperclip
It is conventional to store your uploaded files in public/system, the default configuration in paperclip is:
:rails_root/public/system/:class/:attachment/:id_partition/:style/:filename
but you can change it to another main folder if you want to keep it out of public:
:rails_root/private/:class/:attachment/:id_partition/:style/:filename
Upvotes: 5
Reputation: 61
Rails handles file uploads much like any web framework: it leaves the handling of file uploads up to the web server you are using (Apache, Nginx, etc.). Then when the file upload is complete it gives your framework the location (usually a temp file) of the uploaded file (and stuff like MIME-type). It's up to you to decide what to do with that file. Rails does this by providing you with a Ruby File object in your controller.
If you use a gem like "paperclip" it gives you a bit more control over files out-of-the-box instead of just handling it by yourself, you can have automatic image resizing, or other post-upload hooks, really worth looking into.
If you choose to do it yourself, you'd need controller code that takes the File object (the temp file) and writes that to a different location. So, if you have a multi-part web form that takes a file:
<%= form_tag({:action => :upload}, :multipart => true) do %>
<%= file_field_tag 'picture' %>
<% end %>
You'd end up with a picture
object in your params hash:
params[:picture]
That is the temp file. Rails provides two extra methods to determine the original filename and the MIME-type:
params[:picture].original_filename
params[:picture].content_type
Upvotes: 4