So we have Carrierwave uploading pictures to our local server. Perhaps we want the pictures stored on a third party cloud provider. Amazon S3 and Carrierwave work very well together. This blog post describes how to upload your pictures to the Amazon S3 cloud. Again, thanks to Ryan Bates and Railscasts for the great information.
In order to upload files to Amazon S3, we will be using the Fog Gem. The Carrierwave gem handles the Fog interaction with Amazon S3 behind the scenes.
# encoding: utf-8classAvatarUploader<CarrierWave::Uploader::Base# include CarrierWaveDirect::Uploader# Include RMagick or MiniMagick support:includeCarrierWave::RMagick# include CarrierWave::MiniMagick# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:includeSprockets::Helpers::RailsHelperincludeSprockets::Helpers::IsolatedHelper# Choose what kind of storage to use for this uploader:# storage :filestorage:fogincludeCarrierWave::MimeTypesprocess:set_content_type# Override the directory where uploaded files will be stored.# This is a sensible default for uploaders that are meant to be mounted:defstore_dir"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"end# Provide a default URL as a default if there hasn't been a file uploaded:# def default_url# # For Rails 3.1+ asset pipeline compatibility:# # asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))## "/images/fallback/" + [version_name, "default.png"].compact.join('_')# end# Process files as they are uploaded:# process :scale => [200, 300]## def scale(width, height)# # do something# end# Create different versions of your uploaded files:version:thumbdoprocess:resize_to_limit=>[150,150]endversion:profiledoprocess:resize_to_limit=>[350,350]end# Add a white list of extensions which are allowed to be uploaded.# For images you might use something like this:# def extension_white_list# %w(jpg jpeg gif png)# end# Override the filename of the uploaded files:# Avoid using model.id or version_name here, see uploader/store.rb for details.# def filename# "something.jpg" if original_filename# endend
That is it. Your photos are now added to your Amazon S3 bucket! Just be careful, you only get so much space on the cloud for free. In the next blog post, I will explain how to increase efficiency with a background task via Sidekiq.