我们可以使用阿里云的oss来存放我们项目所使用的资源,如用户头像,音频等文件。
1.首先在阿里云的oss创建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 上面提前创建一个 Bucket
config.aliyun_bucket = "hpd-ddd"
# 是否使用内部连接,true - 使用 Aliyun 主机内部局域网的方式访问 false - 外部网络访问
config.aliyun_internal = false
# 配置存储的地区数据中心,默认: 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