#383 Uploading to Amazon S3 pro
Here I show how to upload files directly to Amazon S3 using CarrierWave Direct and Fog. I then walk through another project which uses jQuery File Upload to handle multiple files and does not use CarrierWave.
- Download:
- source codeProject Files in Zip (2.11 MB)
- mp4Full Size H.264 Video (35.2 MB)
- m4vSmaller H.264 Video (17.1 MB)
- webmFull Size VP8 Video (21.6 MB)
- ogvFull Size Theora Video (41 MB)
Resources
- CarrierWave
- CarrierWaveDirect
- jQuery File Upload
- Amazon Web Services
- Episode 253: CarrierWave File Uploads
- Episode 381: jQuery File Upload
- Episode 366: Sidekiq
terminal
bundle exec sidekiq rails g migration add_image_processed_to_paintings image_processed:boolean rake db:migrate
Gemfile
gem 'carrierwave' gem 'rmagick' gem 'fog' gem 'carrierwave_direct' gem 'sidekiq'
paintings/index.html.erb
<%= direct_upload_form_for @uploader do |f| %> <p><%= f.file_field :image %></p> <p><%= f.submit "Upload Image" %></p> <% end %>
paintings/_form.html.erb
<%= f.hidden_field :key %> <p>File: <%= @painting.image_name %></p>
paintings/_painting.html.erb
<% if painting.image_processed? %> <%= link_to image_tag(painting.image_url(:thumb)), painting %> <% else %> <em>Processing...</em> <% end %>
paintings_controller.rb
def index @paintings = Painting.all @uploader = Painting.new.image @uploader.success_action_redirect = new_painting_url end def new @painting = Painting.new(key: params[:key]) end
uploaders/image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base include CarrierWaveDirect::Uploader include CarrierWave::RMagick # Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility: include Sprockets::Helpers::RailsHelper include Sprockets::Helpers::IsolatedHelper include CarrierWave::MimeTypes process :set_content_type version :thumb do process resize_to_fill: [200, 200] end end
models/painting.rb
class Painting < ActiveRecord::Base attr_accessible :image, :name mount_uploader :image, ImageUploader after_save :enqueue_image def image_name File.basename(image.path || image.filename) if image end def enqueue_image ImageWorker.perform_async(id, key) if key.present? end class ImageWorker include Sidekiq::Worker def perform(id, key) painting = Painting.find(id) painting.key = key painting.remote_image_url = painting.image.direct_fog_url(with_path: true) painting.save! painting.update_column(:image_processed, true) end end end
See the jQuery File Upload project here