class AvatarUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick #使用minimagick处理压缩图片,确保安装magickimage这个东东,ubuntu可以sudo apt-get install magickimage
# Choose what kind of storage to use for this uploader: storage :file # storage :fog
# Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir #定义上传到哪个文件夹下 "#{Rails.root}/public/site_data/#{model.site_id}" end
def filename #图片保存的名字 这里已解决上存相同名字图片覆盖问题 "#{secure_token}.#{file.extension}" if original_filename.present? end
def default_url #可以定义默认图片,如过用户没有上传图片,则可以使用默认的图片 "/sfile/default4.jpg" end
#图片的处理,有不同版本大小,网站可以在不同的地方调用不同的图片大小 version :photo_big do process :resize_to_fit => [480,nil] #fit是先规定图片的长或宽,再等比例缩放没规定的长或宽 end
version :photo_small do process :resize_to_fill => [180,100] #fill硬性规定图片的长或宽 end
# Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: #指定上传文件的格式 def extension_white_list %w(jpg jpeg gif png) end
protected def secure_token var = :"@#{mounted_as}_secure_token" model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid) end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end end