require 'aliyun/oss'
module Aliyun
class AliyunOssAchieve
def self.client
@client = Aliyun::OSS::Client.new(
endpoint: Rails.configuration.application['ALIYUN_OSS_ENDPOINT'],
access_key_id: Rails.configuration.application['ALIYUN_OSS_ACCESS_KEY_ID'],
access_key_secret: Rails.configuration.application['ALIYUN_OSS_ACCESS_KEY_SECRET']
)
end
'''
流式上传
file_key: 文件名, oss文件夹是已文件夹名称+文件名组成, 如product/test.png
io_stream: 文件流
'''
def self.upload_by_io(file_key, io_stream)
bucket_name = Rails.configuration.application['ALIYUN_OSS_BUCKET']
bucket = client.get_bucket(bucket_name)
bucket.put_object(file_key) { |stream| stream << io_stream }
end
'''
图片链接上传
url: 图片链接,需要完整的图片网址
dir: 上传文件夹名称
file_name: 文件名称
'''
def self.upload_by_url(url, dir = nil, file_name = nil)
return if url.blank?
# 获取文件名称
name = file_name.presence || Tools::URL.file_name(url)
file_name = name
unless dir.blank?
file_name = dir + '/' + name
end
response = Faraday.get(url)
upload_by_io(file_name, response.body)
file_name
end
'''
本地上传
url: 图片链接,需要完整的图片网址
dir: 上传文件夹名称
filename: 文件名称
'''
def self.upload_by_local(local_file, dir = nil, file_name = nil)
file_key = dir + '/' + file_name
bucket_name = Rails.configuration.application['ALIYUN_OSS_BUCKET']
bucket = client.get_bucket(bucket_name)
bucket.put_object(file_key, :file => local_file)
end
'''
生成下载链接
file_key: 文件名, oss文件夹是已文件夹名称+文件名组成, 如product/test.png
limit_time: url有效期,单位: 秒
'''
def self.download_url(file_key, limit_time = 100)
# true 表示链接带签名
bucket_name = Rails.configuration.application['ALIYUN_OSS_BUCKET']
bucket = client.get_bucket(bucket_name)
bucket.object_url(file_key, true, limit_time)
end
'''
删除文件
file_key: 文件名, oss文件夹是已文件夹名称+文件名组成, 如product/test.png
'''
def self.delete_oss(file_key)
bucket_name = Rails.configuration.application['ALIYUN_OSS_BUCKET']
bucket = client.get_bucket(bucket_name)
bucket.delete_object(file_key)
end
end
end