阿里云aliyun oss上传文件
require 'aliyun/oss' client = Aliyun::OSS::Client.new( # Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 endpoint: 'https://oss-cn-hangzhou.aliyuncs.com', # 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 access_key_id: ENV['OSS_ACCESS_KEY_ID'], access_key_secret: ENV['OSS_ACCESS_KEY_SECRET'] ) # 填写Bucket名称,例如examplebucket。 bucket = client.get_bucket('examplebucket') # 上传文件。 bucket.put_object('exampleobject.txt', :file => 'D:\\localpath\\examplefile.txt')
require 'find' # 上传多个文件。 # 大概是先遍历整个文件夹 root_path = "/home/tmp/lambda/" Find.find(root_path) do |path| next if path == root_path bucket.put_object(path[root_path..-1], file: path) end 15 Find.find(root_path) do |path| 16 next if path.strip == root_path 17 next if FileTest.directory?(path) 18 puts path 19 puts path[root_path.length..-1] 20 bucket.put_object(path[root_path..-1], :file => path) 21 end
# 判断目标地址有没有文件,如果没有再上传。 buckets = client.list_buckets buckets.each{ |b| puts b.name } # 填写Bucket名称,例如examplebucket。 bucket = client.get_bucket('examplebucket') root_path = "/home/hw/www/examplebucket/shared/public/" local_path = "/home/hw/www/examplebucket/shared/public/system/p/s/" oss_path = "system/p/s/" @arr = [] def list_dir(dir, bucket) objects = bucket.list_objects(:prefix => dir, :delimiter => '/') objects.each do |obj| if obj.is_a?(Aliyun::OSS::Object) # object puts "Object: #{obj.key}" @arr.push obj.key else # common prefix puts "SubDir: #{obj}" list_dir(obj, bucket) # 递归调用list_dir处理子目录。 end end end list_dir(oss_path, bucket) pp @arr Find.find(local_path) do |path| next if path.strip == local_path next if FileTest.directory?(path) puts path object_key = path[root_path.length..-1] if @arr.include?(object_key) puts '存在' else puts '不存在' bucket.put_object(object_key.to_s, file: path.to_s) end end
阅读量: 930
发布于:
修改于:
发布于:
修改于: