ruby-on-railsamazon-s3rails-activestorageruby-on-rails-5.2

How to specify a prefix when uploading to S3 using activestorage's direct upload?


With a standard S3 configuration:

AWS_ACCESS_KEY_ID:        [AWS ID]
AWS_BUCKET:               [bucket name]
AWS_REGION:               [region]
AWS_SECRET_ACCESS_KEY:    [secret]

I can upload a file to S3 (using direct upload) with this Rails 5.2 code (only relevant code shown):

form.file_field :my_asset, direct_upload: true

This will effectively put my asset in the root of my S3 bucket, upon submitting the form.

How can I specify a prefix (e.g. "development/", so that I can mimic a folder on S3)?


Solution

  • 2022 update: as of Rails 6.1 (check this commit - Allow providing a custom key per blob), this is actually supported:

    user.avatar.attach(key: "avatars/#{user.id}.jpg",
                       io:,
                       content_type: "image/jpeg",
                       filename: "avatar.jpg")