Ruby on Rails, Paperclip, Uploadify and S3
I've been doing lots of work with Heroku. Since Heroku only deals with with application side and the filesystem is treated as though it were read-only, file storing has been done through Amazon S3. thoughtbot's Paperclip is being used to make file maintenance easier.
However, since clients nowadays want the fanciness of Web 2.0, the uploads were to have progress bars. So, because the sites were using jQuery the applications ended up being integrated with Uploadify.
Kia Kroas :=: 16 Mar, 2010 04:06:47
I'm under NDA and confidentiality agreements so I won't give any details about the applications themselves. But, here's how to integrate Ruby on Rails with Paper clip with Uploadify with Amazon S3.
Now keep in mind I'm not going to do a step by step tutorial on how to get it to work--I don't have the time for that and this blog isn't exactly targetted toward the beginner programming class anyway. (I don't even have a target audience, this is mostly just for me. If anyone wants to read it, great, if not no loss.) I'll just give you the steps to handle yourself.
Steps (in no particular order):
- Set up Rails, jQuery, Uploadify, S3 Bucket, etc. Duh!
- (optional) Install and set up Paperclip.
- Generate an upload signature for use with Uploadify.
- Set Uploadify with options to work with S3.
- Set up a callback action to listen to the return from S3.
(optional) Setting up Paperclip. If you want to do image manipulations, you'll most likely want to just upload the image and use paperclip's S3 storage system to handle everything. These links may help:
http://timmyc.posterous.com/uploadify-on-rails-with-paperclip
http://jimneath.org/2008/05/15/swfupload-paperclip-and-ruby-on-rails/
Generate an upload signature for use with Uploadify
S3 uses access control policies to handle uploads. Since generally you want your users to upload to your bucket, you'll be doing this over HTTP or HTTPS. S3 has an access control signing system to allow uploads by the public; they call it
Query String Authentication. The easy way to get around this is to just set the bucket you want to be public write, but there's lots of security issues that come out of that, so we'll generate a signature.
def s3_upload
# s3.yml is a file in the config folder, it's formatted for paperclip
s3config = YAML.load_file("#{RAILS_ROOT}/config/s3.yml")
bucket = s3config['production']['bucket']
access_key = s3config['production']['access_key_id']
secret = s3config['production']['secret_access_key']
key = "uploads/"
expiration = 10.hours.from_now.utc.strftime('%Y-%m-%dT%H:%M:%S.000Z')
max_filesize = 30.megabytes
sas = '201' # Tells amazon to redirect after success instead of returning xml
policy = Base64.encode64(
"{'expiration': '#{expiration}',
'conditions': [
{'bucket': '#{bucket}'},
['starts-with', '$key', '#{key}'],
{'success_action_status': '#{sas}'},
['content-length-range', 1, #{max_filesize}],
['starts-with', '$filename', ''],
['starts-with', '$folder', ''],
['starts-with', '$fileext', '']
]}
").gsub(/\n|\r/, '')
signature = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), secret, policy)).gsub(/\n| |\r/, '')
{:access_key => access_key, :key => key, :policy => policy, :signature => signature, :sas => sas, :bucket => bucket}
end
With this, the bucket stays privately writable, but users can upload if the key starts with 'uploads/'. So if you want to see all user uploads, look for keys with that as a prefix. Notice that it returns a hash. I put it in the application controller as a utility function that's used like so:
uploadify = s3_upload
@javascript = "var S3_BUCKET='http://#{uploadify[:bucket]}.s3.amazonaws.com/';\n
var UPLOADIFY = { 'AWSAccessKeyId' : encodeURIComponent(encodeURIComponent('#{uploadify[:access_key]}')),
'key': encodeURIComponent(encodeURIComponent('#{uploadify[:key]}${filename}')),
'policy': encodeURIComponent(encodeURIComponent('#{uploadify[:policy]}')),
'signature': encodeURIComponent(encodeURIComponent('#{uploadify[:signature]}')),
'success_action_status': '#{uploadify[:sas]}',
'folder': '',
'Filename': '' };"
Then I output @javascript into the page that needs the uploadify, usually in the top header. The two javascript variables become global constants, so I can call them from external js files since with jQuery I generally have external javascript files hooked with $(document).ready() rather than inline js. Next, using these options in uploadify.
Set Uploadify with options to work with S3
$("#uploadify_source").uploadify({
'uploader' : '/flash/uploadify.swf',
'buttonImg' : '/images/upload.png',
'cancelImg' : '/images/cancel.png',
'script' : S3_BUCKET,
'fileDataName': 'file',
'scriptData' : TRACK_UPLOADIFY,
'fileDesc' : 'Music',
'fileExt' : '*.mp3;', //list of uploadable filetypes
'onComplete' : uploadify_complete,
'onError': uploadify_error,
'scriptAccess' : 'always',
'queueID' : 'uploadifyQueue',
'auto' : true,
'folder' : '',
'sizeLimit' : 31457280,
'multi' : true
});
function uploadify_error(event, queueID, fileObj, errorObj){
if(errorObj.info == 201){
$.post(CALLBACK_URL, {'_method': 'put', 'file[size]': fileObj.size, 'file[name]': fileObj.name}, function(data){
// do stuff with data
$('#uploadify_source').uploadifyCancel(queueID);
}, 'json');
}
return true;
}
function uploadify_complete(event, queueID, fileObj, response){
$.post(CALLBACK_URL, {'_method': 'put', 'file[size]': fileObj.size, 'file[name]': fileObj.name}, function(data){
// do stuff with data
}, 'json');
}
We need to catch errors because on some platforms, Flash reads a 201 as an error, and Uploadify treats it as an error. The $.post call is sent to the CALLBACK_URL, which I didn't set in the example, but you should when you do. Next up, setting the callback action.
Set up a callback action to listen to the return from S3
Ok, so since we're uploading the file over to S3, our server doesn't even know the file exists. We'll need a way to tell the webserver and database that the file is there. That's what the $.post() call earlier was for. My callback url was just a create action.
def create
@file = SomeModel.new(params[:file])
if @file.save
# render :json => {:success => :data}
else
# render :json => {:failure => :data}
# redirect_to ...
end
end
That's it. Good luck trying to find a more comprehensive article!
Uploadify forum on the topic (This was the only thing I had to work with when I was trying to do it.)
rails-uploadify-s3 example Found it on a quick google for the forum link above. Haven't looked at it, but it looks like an example to get you started.
:: Comments ::
spotman # 60cd54a0b13b36fe1d5ff6b672511383ba51fbd5 @ 27 Apr, 2011 04:26:33
thanks, very helpful!Anon1308677889 # 0eeaf11462420a751a43bc1fa2a6129d9005bf0d @ 21 Jun, 2011 12:38:09
sfsreeju # 8d8b639db48529845be907f2c1ec309af0fb4e60 @ 27 Oct, 2011 05:43:05
Hi, can I know what actually meant by
scriptData : TRACK_UPLOADIFY,
Thanks
Sreejeshmoncler jacket moncler jackets # 72df905c4eda34cc7b5460cf57d5752b03ccf67e @ 01 Dec, 2011 02:35:41
Should a bazaar sports <a href="http://www.moncler4me.com/">moncler jacket</a> designed layer, the reporter sees many a line of sports brand clothing design into the avant-garde, gentle and elements, a change of the past spontaneously and effortlessly. One brand of long T-shirt, all is almost pure color design, and in this year's design, a lot of the broken beautiful element, more add green and lively; <a href="http://www.moncler4me.com/">Moncler Jackets</a>, in the pocket of the zipper ingenuity, adopted the sparkle of the metal elements as decoration, appear very avant-garde. Many brand sportswear, launched a joint body curve skirt outfit, appear woman flavour is dye-in-the-wood. In addition to the details, clothing in the design of collars, cuff place have some processing, swings get, lotus leaf sleeve, add sweet flavor. The reporter interviewed several random customers. The customer is a movement of miss wang brand loyal fans, she told the reporter, this year's these sports brand design she like very much, except in <a href="http://www.moncler4me.com/">moncler jackets</a> occasion wear besides, wear to work is no problem. And also think customer liu, fashionable element always let a person shine at the moment.
moncler 2012 # 72df905c4eda34cc7b5460cf57d5752b03ccf67e @ 01 Dec, 2011 02:36:23
<a href="http://www.cheapmoncler2012.com/">Moncler 2012</a> has spent heavily into brand promotion, not only invited Hong Kong red star Nicholas, superman combination of TWINS, small gas king pan wilber, and waiting for many star Jolin combination bear <a href="http://www.cheapmoncler2012.com/">moncler men</a> ambassador, more in the national scope chose CCTV, hunan TV, anhui, jiangsu TV variety and a number of famous media solution television ads, and in magazines, newspapers, network, car body, street signs such media on the plane advertising, and the large sports sponsorship of, all aspects of the brand communication. To support the development of the terminal, <a href="http://www.cheapmoncler2012.com/">moncler men</a> spent millions stores employ professional advisers to the company, for agents, distributors, a staff and internal market personnel system of professional training, from store location, decorate, recruit, interview, products purchasing, display, promote sales business, enterprise and brand shop comprehensive management and so on various provide guidance.incon # 3d840545269919dc94fc0dc45519c7ee56ac88cd @ 30 Dec, 2011 01:32:32
<a href="http://icqmobilephones.net/">ÑкаÑаÑÑ qip Ð´Ð»Ñ ÑелеÑона</a>
[url=http://icqmobilephones.net/]icq Ð´Ð»Ñ Ð¼Ð¾Ð±Ð¸Ð»Ñного[/url]cholesterolndk # 568241b09f59c3277c2ac51ad1e60ec12a987477 @ 03 Jan, 2012 02:42:42
[url=http://www.healthycholesteroldiets.com]Cholesterol foods[/url]
In case you have been recently identified as having higher cholesterol or even wish to take on more suitable health care to your well-being to not have health and wellness challenges, an example poor cholesterol healthy eating plan will make an enormous big difference. Cholesterol may be a ingredient created by your body in addition to, inside the perfect volume, is known as a essential part of this platforms. Cholesterol is very important to be able to every last wireless, still an inadequate eating routine can certainly results in the body's producing lots of cholesterol which will may bring about severe medical conditions including departure.
A higher a higher level cholesterol is normally risky because the device triggers an improved chance for cardiovascular disease and even cerebral vascular accidents. The great thing is that food plan can certainly greatly cut down cholesterol values but will likewise have any put in advantage of bettering your health and wellness. A considerable amount of health issues will be caused by negative eating plan. Huge hold pressure, digestion trouble together with fatness are usually just a few of the disorders which might be much better by using a healthy diet. By altering whatever you devour in reducing cholesterol you'll end up being enhancing yourself in lots of other locations.
Within a number of events, medicines will play a part around inducing high cholesterol. Nevertheless, most often eating plan and insufficient actions would be the result in. The best possibly cause is certainly the intake of plenty of saturated fats. Even when the explanation for an individual's large cholesterol might be it is partially it will definitely be aided by restoring your diet's recommendations.
Unhealthy excess weight is found in junk foods, cakes, purple food, ova together with dairy, to ensure you have to lower ingestion with these types of cuisine.
Obtain among an example very low cholesterol diet plan.
Dinner
Whole fiber cereal by means of almond exploit. : Unsweetened cereals an excellent source of bran as well as wholemeal are especially beneficial. Avert sugary for cereals. You need to employ non-dairy whole milk to lower cholesterol like almond whole milk or maybe hemp dairy products.
Change coffee beans together with juice -- This may propose further vitamins to all your diet program plus assist to reduce your maintain anxiety. Smoothies can be great while they have more much rather than fruit juice. If it is possible mix your individual so that you can save money however you'll find top notch stow delivered kinds. Make sure that almost any juices you acquire is usually innovative beverages rather than a veggie juice take in that's primarily tasting water. They might be sold very in a similar fashion. Try to be mindful to not ever overdo fresh fruits and also juices while they carry a great deal of fructose, a type of sugar that creates the bodies cells to release insulin as well as, finally, triggers cholesterol to elevate. three Slices connected with whole grain cheers -- If you are using a new extended try to look for a bed that is actually specially designed to smaller cholesterol. Benecol is a superb case study.
Lunch break
A good veg dependent soups, delivered through whole fiber bakery.
Bird salad meal through wholegrain loaf of bread.
Assist along with a couple of a percentage in berries along the lines of strawberries, cherries or grapes.
Meal
Prepared fatty seafood served with vegetables in addition to boiled carrots. - Greasy fish features Omega 3 of which actively shapes cholesterol by the body processes. This kind of tends to make fishes, for example mackerel, an amazing meal relating to the minimum cholesterol eating plan.
During the day it really is good to beverage enough mineral water as well as tea which have been superior for ones health and wellness. When you are eager, choose something to eat like walnuts, pistachio nuts, pumpkin not to mention sunflower seed. A fantastic lead will be to consider several several tones connected with fruit and veggies as they can be.
If you happen to sign up the following pointers for one day sample reduced cholesterol weight loss plan to all your daily healthy eating plan you might shortly profit from a marked improvement on your cholesterol levels and additionally bloodstream pressure. It will immensely decrease your danger regarding critical sickness. It is usually a smart idea to propose a number of lighting working out in your chosen lifestyle, it is advisable to confer with your physician upon the quality of physical exercise this really is right for one simply because it will depend on the seriousness of the illness.