ruby on rails aliyun ossピクチャーアップロードurlアップロードとローカルアップロード


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