ruby-on-rails 把对象放到aws S3 ruby中的特定文件夹

5f0d552i  于 2023-01-22  发布在  Ruby
关注(0)|答案(3)|浏览(150)

我试图使用Aws sdk rails gem上传文件。
一切都很成功,除了我找不到如何使用Ruby SDK将文件上传到特定文件夹的方法。

s3 = Aws::S3::Resource.new
obj = s3.bucket('storagy-teen-dev-us').object("deepak_file")
obj.upload_file('./tmp/aws_test.txt')

这很好用。但是我想在aws bucket中的一个特定目录下创建deepak_file,比如photos。我已经试过下面的方法了,但是不起作用。
obj = s3.bucket('storagy-teen-dev-us').object("photos/deepak_file")

bpsygsoo

bpsygsoo1#

试试这个

s3 = Aws::S3::Resource.new
path = 'photos/deepak_file/aws_test.txt'
s3.bucket('storagy-teen-dev-us').object(path).upload_file(./tmp/aws_test.txt)

你只需要到指定目录的完整路径与文件名.

agxfikkp

agxfikkp2#

require 'aws-sdk-s3' # v1.x

client = Aws::S3::Client.new(region: '...',
                             access_key_id: '...',
                             secret_access_key: '...')

client.put_object(bucket: bucket,
                  key: 'photos/my-pic.jpg',
                  body: File.read(some_image_file),
                  acl: 'private')
uubf1zoe

uubf1zoe3#

简短回答:

client = Aws::S3::Client.new(http_wire_trace: true) // Note: Enable wire_trace only in debug mode.
    
create_bucket_if_missing(client, bucket_name)

client.put_object(
     :bucket => bucket_name,
     :key    => key,
     :body   => File.read(file_path)
   )

def create_bucket_if_missing(client, bucket_name)
  begin
    client.head_bucket(bucket: bucket_name)
    return
  rescue StandardError
    puts "Failed to find bucket #{bucket_name}, creating it"
    client.create_bucket({bucket: bucket_name})
  end
end

相关问题