创建model
#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 => 'yourbucketname' # Paperclip Validations validates_attachment_presence :video validates_attachment_content_type :video, :content_type => ['application/x-shockwave-flash', 'application/x-shockwave-flash', 'application/flv', 'video/x-flv'] end
配置S3相关的配置
#config/s3.yml access_key_id: YOURSECRETACCESSID secret_access_key: YOUR-secRE/TACCe\ssKEy
添加插件
Rails::Initializer.run do |config| ... config.gem 'right_aws', :version => '1.9.0' ... end
执行
sudo rake gems:install sudo rake gems:unpack
Controller和view会如下:
class VideosController < ApplicationController def index @videos = Video.find :all end def new @video = Video.new end def create @video = Video.new(params[:video]) if @video.save flash[:notice] = 'Video has been uploaded' redirect_to :action => 'index' else render :action => 'new' end end def show @video = Video.find(params[:id]) end end # index viewVideos (<%= link_to 'Create new', new_video_path %>)
-
<% for video in @videos %>
- <%= video.video_file_name %> <%= video.video.url %> <%= link_to 'view', video_path(video) %> <% end %>
<%= f.label :video %>
<%= f.file_field :video %>
<%= f.submit %> or <%= link_to 'Cancel', videos_path %>
<% end %> # show view
You need to have <%= link_to 'Flash Player', 'http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash' %> installed to display this video
配置flash player显示视频
- 下载JW FLV MEDIA PLAYER (mediaplayer.zip)
- 复制player.swf到public/flash/player.swf
- 复制swfobject.js 到 public/javascript/swfobject.js
- 修改配置application.html.erb加载swfobject.js
<%= SITE_NAME %> <%= stylesheet_link_tag 'application' %> <%= javascript_include_tag :defaults %> <%= javascript_include_tag 'swfobject' %>
这样你就可以在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
出处