Skip to content

Instantly share code, notes, and snippets.

@edison
Forked from watson/file_resource.rb
Created January 24, 2012 18:35
Show Gist options
  • Save edison/1671769 to your computer and use it in GitHub Desktop.
Save edison/1671769 to your computer and use it in GitHub Desktop.
Example Rails model using Paperclip and storing files on S3. This shows how to correctly set a custom header and saving the file in the correct location after it has been directly uploaded to from the users browser.
class FileResource < ActiveRecord::Base
has_attached_file :attachment,
:storage => :s3,
:bucket => ENV['S3_BUCKET'],
:s3_credentials => { :access_key_id => ENV['S3_KEY'],
:secret_access_key => ENV['S3_SECRET'] },
:path => 'files/:id/:filename',
:url => '/files/:id/:filename'
validates_attachment_presence :attachment
after_create :move_upload_from_temp_to_final_resting_place
protected
def move_upload_from_temp_to_final_resting_place
AWS::S3::Base.establish_connection!(
:access_key_id => ENV['S3_KEY'],
:secret_access_key => ENV['S3_SECRET']
)
old_name = "_temp/#{self.attachment_file_name}"
new_name = self.attachment.path
AWS::S3::S3Object.rename(old_name, new_name, ENV['S3_BUCKET'], :copy_acl => :true)
# WARNING: When ever an attachment is reprocessed by paperclip all its headers/metadata is lost! This also applies to the original!
self.attachment.reprocess! unless self.attachment.styles.empty?
AWS::S3::S3Object.update(new_name, ENV['S3_BUCKET'], :content_disposition => "attachment; filename=\"#{self.attachment_file_name}\"", :access => :public_read)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment