added content-disposition header for uploads on S3

This commit is contained in:
Régis Hanol 2013-08-30 17:27:42 +02:00
parent 1a38f66c7e
commit 9d6cb6aae4

View File

@ -2,13 +2,14 @@ require 'digest/sha1'
require 'open-uri' require 'open-uri'
class S3Store class S3Store
@fog_loaded ||= require 'fog'
def store_upload(file, upload) def store_upload(file, upload)
# <id><sha1><extension> # <id><sha1><extension>
path = "#{upload.id}#{upload.sha1}#{upload.extension}" path = "#{upload.id}#{upload.sha1}#{upload.extension}"
# if this fails, it will throw an exception # if this fails, it will throw an exception
upload(file.tempfile, path, file.content_type) upload(file.tempfile, path, upload.original_filename, file.content_type)
# returns the url of the uploaded file # returns the url of the uploaded file
"#{absolute_base_url}/#{path}" "#{absolute_base_url}/#{path}"
@ -58,9 +59,7 @@ class S3Store
end end
def remove_file(url) def remove_file(url)
return unless has_been_uploaded?(url) remove File.basename(url) if has_been_uploaded?(url)
name = File.basename(url)
remove(name)
end end
def has_been_uploaded?(url) def has_been_uploaded?(url)
@ -102,19 +101,17 @@ class S3Store
raise Discourse::SiteSettingMissing.new("s3_secret_access_key") if SiteSetting.s3_secret_access_key.blank? raise Discourse::SiteSettingMissing.new("s3_secret_access_key") if SiteSetting.s3_secret_access_key.blank?
end end
def get_or_create_directory(name) def get_or_create_directory(bucket)
check_missing_site_settings check_missing_site_settings
@fog_loaded ||= require 'fog' fog = Fog::Storage.new s3_options
fog = Fog::Storage.new generate_options directory = fog.directories.get(bucket)
directory = fog.directories.create(key: bucket) unless directory
directory = fog.directories.get(name)
directory = fog.directories.create(key: name) unless directory
directory directory
end end
def generate_options def s3_options
options = { options = {
provider: 'AWS', provider: 'AWS',
aws_access_key_id: SiteSetting.s3_access_key_id, aws_access_key_id: SiteSetting.s3_access_key_id,
@ -124,22 +121,21 @@ class S3Store
options options
end end
def upload(file, name, content_type=nil) def upload(file, unique_filename, filename=nil, content_type=nil)
args = { args = {
key: name, key: unique_filename,
public: true, public: true,
body: file, body: file
} }
args[:content_disposition] = "attachment; filename=\"#{filename}\"" if filename
args[:content_type] = content_type if content_type args[:content_type] = content_type if content_type
directory.files.create(args)
get_or_create_directory(s3_bucket).files.create(args)
end end
def remove(name) def remove(unique_filename)
directory.files.destroy(key: name) fog = Fog::Storage.new s3_options
end fog.delete_object(s3_bucket, unique_filename)
def directory
get_or_create_directory(s3_bucket)
end end
end end