简体   繁体   中英

put object to a specific folder in aws S3 ruby

I was trying to upload files using Aws sdk rails gem.

Everything is successful except I can not find a way how to upload files to a specific folder using ruby sdk.

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

This works fine. But I want to create the deepak_file inside a particular directory in aws bucket, let's say photos . I already tried the below but not working.

obj = s3.bucket('storagy-teen-dev-us').object("photos/deepak_file")

Try this,

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)

you just need to specify full path of directory with file name.

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')

Short Answer:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM