Where can I save uploaded files in Rails?

I tried to find documentation processing in Rails without success. Here is a link to the File class (indicated by the documents for file_filed_tag): http://api.rubyonrails.org/classes/File.html

I believe that there should be a better set of source documents. My main question is: where can I save a file that is not publicly accessible. I am interested in temporarily uploading files for the "wizards" for users.

+4
source share
2 answers

Only the Rails documentation mentions this. The source that handles downloads is https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/http/upload.rb

You can use the "paperclip" gem to handle the file upload for you:

https://github.com/thoughtbot/paperclip

Usually you save the downloaded files in the public / system mode, the default configuration is in a clip:

:rails_root/public/system/:class/:attachment/:id_partition/:style/:filename 

but you can change it to another main folder if you want to leave it in the public domain:

 :rails_root/private/:class/:attachment/:id_partition/:style/:filename 
+4
source

Rails handles file uploads in the same way as any web infrastructure: it leaves file processing on the web server you use (Apache, Nginx, etc.). Then, when the file download is complete, it gives your structure the location (usually a temporary file) of the downloaded file (and the like, the MIME type). You decide what to do with this file. Rails does this by providing you with a Ruby File object in your controller.

If you use a gem such as "paperclip", it gives you a bit more control over the files out of the box, instead of just processing it yourself, you can have automatic image resizing or other hooks for later downloading, it is really worth exploring.

If you decide to do it yourself, you will need a controller code that takes a File object (temp file) and writes it to another 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 %> 

In the params hash, you get a picture object:

 params[:picture] 

This is a temporary file. Rails provides two additional methods for determining the original file name and MIME type:

 params[:picture].original_filename params[:picture].content_type 
+3
source

Source: https://habr.com/ru/post/1479217/


All Articles