Single file upload using Carrierwave

suggest change

Getting started with file uploads in Rails is quite simple. First, choose a library for managing uploads. The most common ones are CarrierWave and Paperclip. Both are similar in functionality and well documented.

Here is a simple avatar upload with CarrierWave.

After bundle install, type in the console:

rails generate uploader ProfileUploader

This creates a config file at app/uploaders/profile_uploader.rb.

Here you can set up storage (local or cloud), apply image manipulation (for example, generating thumbs with MiniMagick), and set a server-side extension allowlist.

Next, create a migration with a string column user_pic, and mount the uploader on the User model.

mount_uploader :user_pic, ProfileUploader

Next, display a form to upload the avatar (this may be the user edit view):

<%= form_for @user, html: { multipart: true } do |f| %>
  <%= f.file_field :user_pic, accept: "image/png,image/jpeg" %>
  <%= f.submit "update profile pic", class: "btn" %>
<% end %>

Include multipart: true so the form can send the file. On Rails 5.1 and later, form_with does this for a file field. accept is an optional client-side allowlist.

To display the avatar:

<%= image_tag @user.user_pic.url %>

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents