项目地址: https://github.com/jnicklas/carrierwave
gem 'carrierwave', "0.6.2"
bundle install
rails generate uploader Video
生成uploader文件
如果需要处理图片,可增加Minimagick gem
gem 'mini_magick', "3.3"
修改uploader
include CarrierWave::MiniMagick
# Create different versions of your uploaded files:
version :thumb do
process resize_to_fill: [150, 150]
end
version :main do
process resize_to_fill: [600, 400]
end
version :cif do
process resize_to_fill: [320, 240]
end
生成model
rails g scaffold video title:string file:string message_id:integer deleted:boolean user_id:intege
rake db:migrate
bootstrap 格式化Html
rails g bootstrap:themed Videos
修改video model
mount_uploader :file, VideoUploader
引用
u.avatar.url # => '/url/to/file.png'
u.avatar.current_path # => 'path/to/file.png'
u.avatar.identifier # => 'file.png'
修改form表单
<%= form_for @user, :html => {:multipart => true} do |f| %>
<% end %>
修改图片大小的方法
def resize_to_limit(width, height)
process :resize_to_limit => [width, height]
end
def resize_to_fit(width, height)
process :resize_to_fit => [width, height]
end
def resize_to_fill(width, height, gravity='Center')
process :resize_to_fill => [width, height, gravity]
end
def resize_and_pad(width, height, background=:transparent, gravity=::Magick::CenterGravity)
process :resize_and_pad => [width, height, background, gravity]
end
resize_to_limit 保存图片完整性
resize_to_fill 图片大小优先
一个需求:
限制width: 320, 高度任意
process :resize_fo_limit: [320, '']