天天看点

使用Rails插件Paperclip上传视频到亚马逊 S3服务

云服务里亚马逊的S3 和 EC2比较常用的,这里是介绍一个上传插件和S3一起使用的例子。

创建model

配置S3相关的配置

添加插件

Rails::Initializer.run do |config|
  ...  
  config.gem 'right_aws', :version => '1.9.0'
  ...
end
           

执行

sudo rake gems:install 
sudo rake gems:unpack
           

Controller和view会如下:

配置flash player显示视频

[list=1]

[*]下载JW FLV MEDIA PLAYER ([url=http://scottmotte.com/wp-content/uploads/2008/11/tmediaplayer.zip]mediaplayer.zip[/url])

[*]复制player.swf到public/flash/player.swf

[*]复制swfobject.js 到 public/javascript/swfobject.js

[*]修改配置application.html.erb加载swfobject.js

[/list]

<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title><%= SITE_NAME %></title>
  <%= stylesheet_link_tag 'application' %>
	<%= javascript_include_tag :defaults %>
	<%= javascript_include_tag 'swfobject' %>
</head>
           

这样你就可以在http://localhost:3000/videos进行上传操作了

关于开发环境和生产环境

通过在配置yml来区分开发和生产环境往往是不错的办法

当然,这里有一个前提,就是有一个settings.yml用来加载load_config.rb file

设置如下:

APP_CONFIG = YAML.load_file(“#{RAILS_ROOT}/config/settings.yml”)[RAILS_ENV].symbolize_keys
           
#In config/settings.yml
development: &non_production_settings
  site_url: http://localhost:3000
  site_name: Site
  admin_email: [email protected]
  bucket: yourappdevelopment

test:
  <<: *non_production_settings

production:
  site_url: http://domain.com
  site_name: Site
  admin_email: [email protected]
  bucket: yourappproduction 
           
#In video.rb
class Video < ActiveRecord::Base

  # Paperclip
  # http://www.thoughtbot.com/projects/paperclip
  has_attached_file :video,
    :storage => :s3,
    :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
    :path => ":attachment/:id/:style/:basename.:extension",
    :bucket => APP_CONFIG[:bucket]
end
           

[url=http://scottmotte.com/archives/181.html] 出处[/url]