我們可以使用阿里云的oss來存放我們項目所使用的資源,如用戶頭像,音頻等文件李皇。
1.首先在阿里云的oss創(chuàng)建bucket
bucket設為公共讀温学。
2.安裝gem
gem 'carrierwave'
gem 'carrierwave-aliyun'
3.配置config/initializers/carrierwave.rb
CarrierWave.configure do |config|
config.storage = :aliyun
config.aliyun_access_id = "LTAIsvndsd9GGs1J"
config.aliyun_access_key = '2UuuxL6NSbjZ9jMufHJObSvmtd0VYK'
# 你需要在 Aliyum OSS 上面提前創(chuàng)建一個 Bucket
config.aliyun_bucket = "hpd-ddd"
# 是否使用內部連接,true - 使用 Aliyun 主機內部局域網的方式訪問 false - 外部網絡訪問
config.aliyun_internal = false
# 配置存儲的地區(qū)數(shù)據(jù)中心钙畔,默認: cn-hangzhou
config.aliyun_area = "cn-shenzhen"
# 使用自定義域名茫陆,設定此項,carrierwave 返回的 URL 將會用自定義域名
# 自定義域名請 CNAME 到 you_bucket_name.oss-cn-hangzhou.aliyuncs.com (you_bucket_name 是你的 bucket 的名稱)
config.aliyun_host = "https://hpd-ddd.oss-cn-shenzhen.aliyuncs.com"
# Bucket 為私有讀取請設置 true擎析,默認 false簿盅,以便得到的 URL 是能帶有 private 空間訪問權限的邏輯
#config.aliyun_private_read = true
end
4.配置app/uploaders/avatar_uploader.rb
class AvatarUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
# 存儲的類型是文件
#storage :file
storage :aliyun
# 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
if Rails.env.production?
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
else
"development/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
# Provide a default URL as a default if there hasn't been a file uploaded:
def default_url(*args)
# For Rails 3.1+ asset pipeline compatibility:
# ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
"http://hpd-ddd.oss-cn-shenzhen.aliyuncs.com/uploads/app_user/avatar/default_user_icon.png"
end
# Process files as they are uploaded:
# process scale: [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process resize_to_fit: [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# 圖片格式接受白名單
# def extension_whitelist
# %w(jpg jpeg gif png)
# end
# Override the filename of the uploaded files:
# # Avoid using model.id or version_name here, see uploader/store.rb for details.
def filename
"#{model.id}__#{Time.now.to_i}.#{original_filename.split(".").last}" if original_filename
end
end
6.設置model
class AppUser < ApplicationRecord
mount_uploader :avatar, AvatarUploader
end
6.存取
存
user = AppUser.new
user.avatar = params[:avatar]
user.save
取
user.avatar.url