List S3 contents and download links in Rails

This post explains how to iterate over the contents of an AWS S3 bucket and generate download links for each object. This example uses aws-sdk version 2. At the time of writing, version 3 is the latest but there’s still a lot of legacy apps that use v2.

Here’s the code:

1
2
3
4
5
6
7
8
9
10
bucket = Aws::S3::Bucket.new(ENV['S3_CSV_BUCKET_NAME'])

bucket.objects.each do |obj|
    puts obj.presigned_url(
    :get, 
    expires_in: 1200, # 20 mins
    response_content_type: 'text/csv',
    response_content_disposition: "attachment; filename=#{obj.key}"
    )
end

First, we initialize an Aws::S3::Bucket instance using the bucket name. Next, we call the objects method which returns a collection of all the objects in the bucket. We can then iterate over the collection and call presigned_url to generate download links for each object.