I'm having a hell of a time working with the aws-sdk documentation, all of the links I follow seem outdated and unusable.
我正忙着使用aws-sdk文档,我所遵循的所有链接都显得过时且无法使用。
I'm looking for a straight forward implementation example of uploading an image file to an S3 bucket in Ruby.
我正在寻找一个直接的实现示例,将图像文件上传到Ruby中的S3存储桶。
- let's say the image path is
screenshots/image.png
- 让我们说图像路径是screenshots / image.png
- and I want to upload it to the bucket
my_bucket
- 我想把它上传到桶my_bucket
- AWS creds live in my ENV
- AWS信誉存在于我的ENV中
Any advice is much appreciated.
任何建议都非常感谢。
1 个解决方案
#1
35
Here is how you can upload a file from disk to the named bucket and key:
以下是如何将文件从磁盘上传到指定的存储桶和密钥:
s3 = Aws::S3::Resource.new
s3.bucket('my_bucket').object('key').upload_file('screenshots/image.png')
That is the simplest method. You should replace 'key' with the key you want it stored with in Amazon S3. This will automatically upload large files for you using the multipart upload APIs and will retry failed parts.
这是最简单的方法。您应该将“key”替换为您希望它存储在Amazon S3中的密钥。这将使用分段上传API自动为您上传大文件,并将重试失败的部分。
If you prefer to upload always using PUT object, you can call #put
or use an Aws::S3::Client
:
如果您希望始终使用PUT对象上传,可以调用#put或使用Aws :: S3 :: Client:
# using put
s3 = Aws::S3::Resource.new
File.open('screenshots/image.png', 'rb') do |file|
s3.bucket('my_bucket').object('key').put(body:file)
end
# using a client
s3 = Aws::S3::Client.new
File.open('screenshots/image.png', 'rb') do |file|
s3.put_object(bucket:'my_bucket', key:'key', body:file)
end
Also, the API reference documentation for the v2 SDK is here: http://docs.aws.amazon.com/sdkforruby/api/index.html
此外,v2 SDK的API参考文档位于:http://docs.aws.amazon.com/sdkforruby/api/index.html
#1
35
Here is how you can upload a file from disk to the named bucket and key:
以下是如何将文件从磁盘上传到指定的存储桶和密钥:
s3 = Aws::S3::Resource.new
s3.bucket('my_bucket').object('key').upload_file('screenshots/image.png')
That is the simplest method. You should replace 'key' with the key you want it stored with in Amazon S3. This will automatically upload large files for you using the multipart upload APIs and will retry failed parts.
这是最简单的方法。您应该将“key”替换为您希望它存储在Amazon S3中的密钥。这将使用分段上传API自动为您上传大文件,并将重试失败的部分。
If you prefer to upload always using PUT object, you can call #put
or use an Aws::S3::Client
:
如果您希望始终使用PUT对象上传,可以调用#put或使用Aws :: S3 :: Client:
# using put
s3 = Aws::S3::Resource.new
File.open('screenshots/image.png', 'rb') do |file|
s3.bucket('my_bucket').object('key').put(body:file)
end
# using a client
s3 = Aws::S3::Client.new
File.open('screenshots/image.png', 'rb') do |file|
s3.put_object(bucket:'my_bucket', key:'key', body:file)
end
Also, the API reference documentation for the v2 SDK is here: http://docs.aws.amazon.com/sdkforruby/api/index.html
此外,v2 SDK的API参考文档位于:http://docs.aws.amazon.com/sdkforruby/api/index.html