使用适用于 Ruby 的 AWS 开发工具包上传对象 - Amazon Simple Storage Service

本指南不再进行更新。有关当前信息和说明,请参阅新的 Amazon S3 用户指南

使用适用于 Ruby 的 AWS 开发工具包上传对象

适用于 Ruby 的 AWS 开发工具包(版本 3)通过两种方式将对象上传到 Amazon S3。第一种方式使用托管的文件上传程序,从而能轻松从磁盘上传任何大小的文件。使用托管文件上传程序方法:

  1. 创建 Aws::S3::Resource 类的实例。

  2. 按存储桶名称和键引用目标对象。位于存储桶中的对象具有可识别每个对象的唯一密钥。

  3. 在对象上调用 #upload_file

require 'aws-sdk-s3' # Uploads an object to a bucket in Amazon Simple Storage Service (Amazon S3). # # Prerequisites: # # - An S3 bucket. # - An object to upload to the bucket. # # @param s3_client [Aws::S3::Resource] An initialized S3 resource. # @param bucket_name [String] The name of the bucket. # @param object_key [String] The name of the object. # @param file_path [String] The path and file name of the object to upload. # @return [Boolean] true if the object was uploaded; otherwise, false. # @example # exit 1 unless object_uploaded?( # Aws::S3::Resource.new(region: 'us-east-1'), # 'doc-example-bucket', # 'my-file.txt', # './my-file.txt' # ) def object_uploaded?(s3_resource, bucket_name, object_key, file_path) object = s3_resource.bucket(bucket_name).object(object_key) object.upload_file(file_path) return true rescue StandardError => e puts "Error uploading object: #{e.message}" return false end

适用于 Ruby 的 AWS 开发工具包(版本 3)上传对象的第二种方式是使用 Aws::S3::Object#put 方法。如果对象为字符串或者为不是磁盘上的文件的 I/O 对象,此方式很有用。要使用此方法,请执行以下操作:

  1. 创建 Aws::S3::Resource 类的实例。

  2. 按存储桶名称和键引用目标对象。

  3. 调用 #put,从而传入字符串或 I/O 对象。

require 'aws-sdk-s3' # Uploads an object to a bucket in Amazon Simple Storage Service (Amazon S3). # # Prerequisites: # # - An S3 bucket. # - An object to upload to the bucket. # # @param s3_client [Aws::S3::Resource] An initialized S3 resource. # @param bucket_name [String] The name of the bucket. # @param object_key [String] The name of the object. # @param file_path [String] The path and file name of the object to upload. # @return [Boolean] true if the object was uploaded; otherwise, false. # @example # exit 1 unless object_uploaded?( # Aws::S3::Resource.new(region: 'us-east-1'), # 'doc-example-bucket', # 'my-file.txt', # './my-file.txt' # ) def object_uploaded?(s3_resource, bucket_name, object_key, file_path) object = s3_resource.bucket(bucket_name).object(object_key) File.open(file_path, 'rb') do |file| object.put(body: file) end return true rescue StandardError => e puts "Error uploading object: #{e.message}" return false end