Using Uploadify and CarrierWave together is a beautiful combination. You can easily leverage CarrierWave's image caching system to store the inline uploads from Uploadify.
The focus of this post is on the CarrierWave side, so we will ignore the Uploadify settings. They are just the standard ones anyway. I am also going to skip all the stuff you need to do to get the authenticity tokens working. If you need to set that up, see
this post.
To get started, as always, we will need an uploader. This is the basic one we will use for this example.
class PhotoUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :s3
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
process :resize_to_fit => [200, 200]
version :thumb do
process :resize_to_fill => [60, 60]
end
def extension_white_list
%w(jpg jpeg gif png)
end
end We then need to attach our uploader to an object. In our example we use a Photo model with the uploader mounted on "image", but you can attach it to any model that is part of your form.
#migration
create_table :photos do |t|
t.string :image
t.timestamps
end
#model
class Photo < ActiveRecord::Base
mount_uploader :image, PhotoUploader
end Now we need a simple controller action to receive the post from Uploadify.
class PhotosController < ApplicationController
skip_before_filter :verify_authenticity_token
def create
photo = Photo.new(params[:photo])
render :partial => 'photo', :locals => { :photo => photo }
end
end This is where the real magic happens. We are going to create the Photo object so CarrierWave will store the upload in its temporary folder, but we won't save it. That is because we don't want to actually persist the object to the database until the full form is posted. Instead, we will return the cache location of the saved file.
You can return it any way you want: text, json, partial, whatever. The important thing is to send back the "image_cache" location so that it can be plugged into an input and posted up with the real form via the "onComplete" hook in uploadify.
Then when you make the real form post it will attach the temporary file. You can also use this method for multiple file uploads.