Connect to S4 with Ruby
Uses the AWS SDK for Ruby 3.x. The code below can be placed in a single file and run in order.
Prerequisites
- Create a bucket in the console;
- Create a sub-user and AccessKey, and grant the sub-user access to this bucket. A new sub-user has no permissions;
- Put the keys in environment variables instead of writing them in code:
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"Install
gem install aws-sdk-s3The examples on this page were tested on Ruby 3.1 and aws-sdk-s3 1.245.
Connect to S4
require "aws-sdk-s3"
S3 = Aws::S3::Client.new(
endpoint: "https://s3.bitiful.net",
region: "cn-east-1",
access_key_id: ENV.fetch("S4_ACCESS_KEY"),
secret_access_key: ENV.fetch("S4_SECRET_KEY")
)
BUCKET = "my-bucket"Aws::S3::Client is thread-safe; create one per process.
Upload files
An object with the same name is overwritten directly. If ContentType is left empty, S4 detects it automatically.
# Upload a text string
S3.put_object(
bucket: BUCKET,
key: "docs/hello.txt",
body: "你好,S4",
content_type: "text/plain; charset=utf-8"
)
# Upload a local file, setting cache time and custom metadata
File.open("photo.jpg", "rb") do |f|
S3.put_object(
bucket: BUCKET,
key: "images/photo.jpg",
body: f,
content_type: "image/jpeg",
cache_control: "max-age=86400",
metadata: { "author" => "bitiful" }
)
endUpload large files
Use multipart upload for files larger than 100 MB: parts can upload concurrently, and a failed part is the only one you need to retry. Each part is 5 MiB to 20 GiB, with up to 10000 parts.
# Split automatically above 16 MiB
transfer = Aws::S3::TransferManager.new(client: S3)
transfer.upload_file(
"video.mp4",
bucket: BUCKET,
key: "videos/video.mp4",
multipart_threshold: 16 * 1024 * 1024,
content_type: "video/mp4",
progress_callback: ->(bytes, totals) { puts "#{bytes.sum * 100 / totals.sum}%" }
)Download files
Download private files with your secret key. To read only part of a file, use Range instead of downloading the whole file.
# Read as a string
puts S3.get_object(bucket: BUCKET, key: "docs/hello.txt").body.read
# Save to a file
S3.get_object(bucket: BUCKET, key: "videos/video.mp4", response_target: "video-copy.mp4")
# Read only the first 1 KiB
part = S3.get_object(bucket: BUCKET, key: "videos/video.mp4", range: "bytes=0-1023")
puts part.content_rangeList files
Each page returns 100 entries by default and 1000 at most; always use a paginator to page through results. Delimiter supports only /.
# List all objects under a prefix, paging automatically
S3.list_objects_v2(bucket: BUCKET, prefix: "images/").each do |page|
page.contents.each { |obj| puts "#{obj.key} #{obj.size} #{obj.last_modified}" }
end
# List only the top-level directories
root = S3.list_objects_v2(bucket: BUCKET, delimiter: "/")
root.common_prefixes.each { |p| puts "Directory #{p.prefix}" }Get file information
Retrieve metadata without downloading the content. You can also use this to check whether an object exists.
def exists?(key)
S3.head_object(bucket: BUCKET, key: key)
true
rescue Aws::S3::Errors::NotFound
false
endCopy and move
Copying is done server-side, so data does not pass through your machine. Move is an S4 extension: append ?move=true to CopySource. It only changes the location without copying data, regardless of file size. See Move and rename objects.
require "erb"
# The object key in copy_source must be URL-encoded, keeping /
def copy_source(key)
"#{BUCKET}/#{key.split('/', -1).map { |p| ERB::Util.url_encode(p) }.join('/')}"
end
# Copy
S3.copy_object(bucket: BUCKET, key: "images/photo-copy.jpg", copy_source: copy_source("images/photo.jpg"))# Move / rename: S4 extension, no data copied
S3.copy_object(
bucket: BUCKET,
key: "archive/photo.jpg",
copy_source: "#{copy_source('images/photo-copy.jpg')}?move=true"
)Delete files
Deleted objects cannot be recovered. A batch delete handles up to 1000 keys at a time; if you lack write permission on any one key, the whole batch returns 403.
# Delete one object
S3.delete_object(bucket: BUCKET, key: "docs/hello.txt")
# Batch delete, up to 1000 objects at a time
keys = ["images/a.jpg", "images/b.jpg"]
result = S3.delete_objects(
bucket: BUCKET,
delete: { objects: keys.map { |k| { key: k } }, quiet: true }
)
result.errors.each { |e| puts "#{e.key} #{e.code} #{e.message}" }Presigned URLs
A presigned URL embeds the authorization in the link, so the holder can upload or download without a secret key. It is valid for up to 7 days. If you sign Content-Type for an upload, the client must send exactly the same value.
presigner = Aws::S3::Presigner.new(client: S3)
# Download URL, valid for 1 hour, with a specified file name
get_url = presigner.presigned_url(
:get_object,
bucket: BUCKET,
key: "images/photo.jpg",
expires_in: 3600,
response_content_disposition: 'attachment; filename="photo.jpg"'
)
puts get_url
# Upload URL, valid for 10 minutes; the client sends a PUT to it
put_url = presigner.presigned_url(:put_object, bucket: BUCKET, key: "uploads/avatar.jpg", expires_in: 600)
puts put_urlPresigned URLs with extension parameters
Extension parameters such as CoreIX processing parameters, rate limits, and request limits must be added before signing. Appending them after signing returns SignatureDoesNotMatch.
require "uri"
# Generate a download URL with S4 extension parameters; they are included in the signature
def presign_with(key, params, expires_in: 3600)
signer = Aws::Sigv4::Signer.new(
service: "s3",
region: "cn-east-1",
access_key_id: ENV.fetch("S4_ACCESS_KEY"),
secret_access_key: ENV.fetch("S4_SECRET_KEY"),
uri_escape_path: false
)
path = key.split("/", -1).map { |p| ERB::Util.url_encode(p) }.join("/")
query = params.map { |k, v| "#{k}=#{ERB::Util.url_encode(v.to_s)}" }.join("&")
signer.presign_url(
http_method: "GET",
url: "https://#{BUCKET}.s3.bitiful.net/#{path}?#{query}",
expires_in: expires_in,
body_digest: "UNSIGNED-PAYLOAD"
).to_s
end
puts presign_with("images/photo.jpg", {
"w" => 500, # CoreIX: width 500 px
"fmt" => "webp", # CoreIX: convert to WebP
"x-bitiful-limit-rate" => 1_048_576, # Per-connection rate limit of 1 MiB/s
"x-bitiful-max-requests" => 3 # At most 3 accesses
})Conditional writes
Conditional writes prevent concurrent overwrites. When the condition is not met, S4 returns 412. See Conditional requests.
begin
# Write only if the object does not exist, to prevent overwriting
S3.put_object(bucket: BUCKET, key: "locks/job", body: "me", if_none_match: "*")
rescue Aws::S3::Errors::PreconditionFailed
puts "Object already exists"
endHandle errors
For the meaning of each error code, see Error codes and troubleshooting. Rate limiting returns 429 TooManyRequest; catch it and retry with backoff.
begin
S3.get_object(bucket: BUCKET, key: "not-exists.txt")
rescue Aws::S3::Errors::NoSuchKey
puts "Object does not exist"
rescue Aws::S3::Errors::ServiceError => e
puts "#{e.context.http_response.status_code} #{e.code} #{e.message}"
rescue Seahorse::Client::NetworkingError => e
puts "Network error: #{e.message}"
endFAQ
How do I configure Rails Active Storage
In config/storage.yml, use service: S3, set endpoint to https://s3.bitiful.net and region to cn-east-1, and fill in the keys and bucket.
Returns 403 AccessDenied
The sub-user has no permission on this bucket or directory. See Sub-user permissions. Creating and deleting buckets can only be done in the console.
Returns SignatureDoesNotMatch
The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the checklist.
Download speed is low
Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a CDN to serve visitors.
Related documentation
Full reference for request limits, rate limits, Simul-Transfer, and other parameters.
Checklists for 403, SignatureDoesNotMatch, and other issues.
Support status and differences for each operation.
Recommended practices for direct uploads from browsers and apps.