Class: CarrierWave::Storage::Aliyun::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/carrierwave/storage/aliyun.rb

Constant Summary collapse

PATH_PREFIX =
%r{^/}

Instance Method Summary collapse

Constructor Details

#initialize(uploader) ⇒ Connection

Returns a new instance of Connection.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/carrierwave/storage/aliyun.rb', line 11

def initialize(uploader)
  @uploader = uploader
  @aliyun_access_id    = uploader.aliyun_access_id
  @aliyun_access_key   = uploader.aliyun_access_key
  @aliyun_bucket       = uploader.aliyun_bucket
  @aliyun_area         = uploader.aliyun_area || 'cn-hangzhou'
  @aliyun_private_read = uploader.aliyun_private_read

  # Host for get request
  @aliyun_host = uploader.aliyun_host || "http://#{@aliyun_bucket}.oss-#{@aliyun_area}.aliyuncs.com"

  unless @aliyun_host.include?('//')
    fail "config.aliyun_host requirement include // http:// or https://, but you give: #{@aliyun_host}"
  end
end

Instance Method Details

#delete(path) ⇒ Object

删除 Remote 的文件

params:

  • path - remote 存储路径

returns: 图片的下载地址



61
62
63
64
65
# File 'lib/carrierwave/storage/aliyun.rb', line 61

def delete(path)
  path.sub!(PATH_PREFIX, '')
  private_client.delete_object(path)
  path_to_url(path)
end

#get(path, &block) ⇒ Object

读取文件 params:

  • path - remote 存储路径

returns: Aliyun::OSS::Object



49
50
51
52
# File 'lib/carrierwave/storage/aliyun.rb', line 49

def get(path, &block)
  path.sub!(PATH_PREFIX, '')
  private_client.get_object(path){ |content| yield content if block_given?}
end

#path_to_url(path) ⇒ Object

根据配置返回完整的上传文件的访问地址



69
70
71
# File 'lib/carrierwave/storage/aliyun.rb', line 69

def path_to_url(path)
  [@aliyun_host, path].join('/')
end

#private_get_url(path) ⇒ Object

私有空间访问地址,会带上实时算出的 token 信息 有效期 3600s



75
76
77
78
# File 'lib/carrierwave/storage/aliyun.rb', line 75

def private_get_url(path)
  path.sub!(PATH_PREFIX, '')
  public_client.object_url(path, true, 3600)
end

#put(path, file, options = {}) ⇒ Object

上传文件 params:

  • path - remote 存储路径

  • file - CarrierWave::SanitizedFile

  • options:

    • content_type - 上传文件的 MimeType,默认 ‘image/jpg`

returns: 图片的下载地址



35
36
37
38
39
40
41
42
43
# File 'lib/carrierwave/storage/aliyun.rb', line 35

def put(path, file, options = {})
  path.sub!(PATH_PREFIX, '')
  opts = {
    content_type: options[:content_type] || 'image/jpg',
    file: file.path
  }
  private_client.put_object(path, opts)
  path_to_url(path)
end