Uploading Files in Rails
Uploading files from a form is a very common task(i.e uploading images, files etc). As you may already know that you need to set
multipart/form-data, if you want to upload files from a form. Similarly in rails, you need to set it in case of
form_tag, while if you are using
form_for, it will be added automatically. Example
<%= form_tag({action: :save_to_server}, multipart: true) do %>
<%= file_field_tag 'cover_pic' %>
<% end %>
<%= form_for @blog do |f| %>
<%= f.file_field :cover_pic %>
<% end %>
So here file_field (model oriented) and form_field_tag (Stand alone) are used for taking file as an input. When the request goes to server the params of file will contain the original_filename (attribute containing the name of the file) and content_type (contains the MIME type of uploaded file). You can save the file at server and then you can perform any action you required like saving the file on s3 or taking thumbnails of image. Here is a code of how to deal with it at server.
def save_to_server
uploaded_file = params[:blog][:cover_pic]
File.open(Rails.root.join('public', 'pics', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_file.read)
end
end
While dealing with ajax, you need to set the variable
remote: true. As in Rails, serialization is done by javascript, which is unable to read files from system. So for this purpose, most commonly an invisible iframe is used to be served as a target for the form submission.
To know more about Rails Form Helpers. Click on the link given below.
Form Helpers in Rails
0 Comment(s)