Last Updated: November 27, 2018
·
2.981K
· João Marcelo Oliveira de Souza

Change downloaded file name (content disposition) with Paperclip and S3

If you're using Rails and Paperclip with S3, you can choose what is going to be the name of the downloaded file by setting the "content disposition" header:

class User < ActiveRecord::Base
  has_attached_file :avatar, s3_headers: -> avatar { {
    content_type:        'image/jpeg',
    content_disposition: 'attachment; filename="default_name.jpg"'
  } }
end

The content disposition is set at upload time, but you can change it later:

user = User.find(id)
s3_object = user.avatar.s3_object
s3_object.copy_to(
  s3_object,
  metadata_directive: 'REPLACE',
  content_disposition: 'attachment; filename="new_name.jpg")'

You must "replace" the metadata, even if blank, otherwise S3 won't allow you to copy the file over itself (will raise an error).