Uploading images to Cloudinary using Rails and Carrierwave
Sometimes we need to upload our images to cloud storage like Amazon S3, but like me, I have a limitation because I don’t have any credit card or paypal account. Cloudinary gives us a chance to store our images with free plan (and also no credit card required).
After signed up to cloudinary with free plan, we’ve got cloud name and a pair of API Key and API Secret, it will be used for our application. Let’s create our app rails new cloudinary
and add several gems to Gemfile
# add these following gems
gem 'cloudinary'
gem 'rmagick'
gem 'carrierwave'
then run the bundle command to install it.
After that, we need to define the cloudinary configuration by creating a file named cloudinary.yml
in config
directory
development:
cloud_name: put_your_cloud_name_here
api_key: put_your_api_key_here
api_secret: put_your_api_secret_here
production:
cloud_name: put_your_cloud_name_here
api_key: put_your_api_key_here
api_secret: put_your_api_secret_here
Let’s create a new resource to serve the upload image function, we can create it by using scaffold rails g scaffold article title:string content:text image:string
and run the migration rake db:migrate && rake db:create
Create a carrierwave uploader to handle the upload rails g uploader article
and alter its config app/uploader/article_uploader.rb
In this case, we want to create 4 versions of image so we need to crop or uploaded image into 4 different size (thumbnail, mini_thumbnail, and detail) using resize_to_fill
.
# encoding: utf-8
class ArticleUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
include Cloudinary::CarrierWave
# Crop to 275px, 206px
version :thumbnail do
process resize_to_fill: [275, 206]
end
# crop to 62px, 62px
version :mini_tumbnail do
process resize_to_fill: [62, 62]
end
# crop to 870px, 261px
version :detail do
process resize_to_fill: [870, 261]
end
# Allowed image format
def extension_white_list
%w(jpg jpeg gif png)
end
end
Move to our Article model in app/models/article.rb
add this following line
# for handling the upload we need to mount the uploader for image field
# :image (our field in the table for storing the image data)
# ArticleUploader (we have created it above)
mount_uploader :image, ArticleUploader
Next, we should change the image form field from text to file field, alter this file app/views/articles/_form.html.erb
# find the image field and change the text field to file field
f.file_field :image
Alter the show view here app/views/articles.html.erb
<h2><%= @article.title %></h2>
<p><%= @article.content %></p>
<!-- Show the image here -->
<%= image_tag @article.image.url %>
<%= image_tag @article.image.url(:thumbnail) %>
<%= image_tag @article.image.url(:mini_thumbnail) %>
<%= image_tag @article.image.url(:detail) %>
We have done our application, start your app and try to upload your image. If you’ve done you code correctly, you can see that you image url is on cloudinary.