这是我的代码:
require 'aws-sdk-core'
Aws.config = {
:access_key_id => MY_ACCESS_KEY
:secret_access_key => MY_SECRET_KEY,
:region => 'us-west-2'
}
s3 = Aws::S3.new
resp = s3.put_object(
:bucket => "mybucket",
:key => "myfolder/upload_me.sql",
:body => "./upload_me.sql"
)
现在,上面的代码运行并创建一个键myfolder/upload_me.sql
,它只写了一行,而./upload_me.sql
是错误的。文件upload_me.sql
有几行。
预期的行为是将文件upload_me.sql
上传为mybucket/myfolder/upload_me.sql
。但它只是将一行写入mybucket/myfolder/upload_me.sql
,即./upload_me.sql
现在,如果我省略:body
部分如下:
s3 = Aws::S3.new
resp = s3.put_object(
:bucket => "mybucket",
:key => "myfolder/upload_me.sql",
)
然后它只创建并清空一个名为mybucket/myfolder/upload_me.sql
的密钥,它甚至不能下载(好吧,即使它被下载,它也没用)
你能指出我哪里出错吗?
以下是put_object
方法:http://docs.aws.amazon.com/sdkforruby/api/Aws/S3/V20060301.html#put_object-instance_method
更新 如果我尝试使用AWS-CLI上传相同的文件,它会被正常上传。这是命令:
aws s3api put-object --bucket mybucket --key myfolder/upload_me.sql --body ./upload_me.sql
答案 0 :(得分:8)
所以,在这个问题上度过一个令人沮丧的星期天下午之后,我终于破解了它。我真正需要的是 :body => IO.read("./upload_me.sql")
所以我的代码如下所示:
s3 = Aws::S3.new
resp = s3.put_object(
:bucket => "mybucket",
:key => "myfolder/upload_me.sql",
:body => IO.read("./upload_me.sql")
)
答案 1 :(得分:1)
body变量是将写入S3的内容。因此,如果您将文件发送到S3,则需要使用File.read(" upload_me.sql")类似地手动加载。
s3 = Aws::S3.new
resp = s3.put_object(
:bucket => "mybucket",
:key => "myfolder/upload_me.sql",
:body => File.read("./upload_me.sql")
)
根据文档,另一种方法是在存储桶上使用write。
s3 = AWS::S3.new
key = File.basename(file_name)
s3.buckets["mybucket"].objects[key].write(:file => "upload_me.sql")
答案 2 :(得分:0)
另一种方式是
AWS.config(
:access_key_id => 'MY_ACCESS_KEY',
:secret_access_key => 'MY_SECRET_KEY',
)
#Set the filename
file_name = 'filename.txt'
#Set the bucket name
s3_bucket_name = 'my bucket name'
#If file has to go in some specific folder
bucket_directory = 'key or folder'
begin
s3 = AWS::S3.new
#Check if directory name has provided and Make an object in your bucket for your upload
if bucket_directory == ''
bucket_obj = s3.buckets[s3_bucket_name].objects[bucket_directory]
else
bucket_obj = s3.buckets[s3_bucket_name].objects["#{bucket_directory}/#{file_name}"]
end
# Upload the file
bucket_obj.write(:file => file_name)
puts "File was successfully uploaded : #{bucket_obj}"
rescue Exception => e
puts "There was an error in uploading file: #{e}"
end
答案 3 :(得分:0)
可能没有找到文件,因为路径是相对的。 这是一种奇怪的行为,界面试图做出太多决定。
我可以向你保证这有效(v3):
client = Aws::S3::Client.new(...)
client.put_object(
body: './existing_file.txt',
bucket: 'kick-it',
key: 'test1.txt'
) # kick-it:/test1.txt contains the same as the contents of existing_file.txt
client.put_object(
body: './non_existing_file.txt',
bucket: 'kick-it',
key: 'test2.txt'
) # kick-it:/test2.txt contains just the string './non_existing_file.txt'
如果你问我,在这两种情况下都使用 body 是一个错误的决定。