Skip to content

Instantly share code, notes, and snippets.

@sulmanweb
Created September 15, 2019 20:20
Show Gist options
  • Save sulmanweb/f555a13560e0526c0ec83fdaf18e4de0 to your computer and use it in GitHub Desktop.
Save sulmanweb/f555a13560e0526c0ec83fdaf18e4de0 to your computer and use it in GitHub Desktop.
AwsUploader class to directly upload url or file to s3. It Requires HTTParty and aws_sdk gems to be installed.
require 'aws-sdk'
require 'HTTParty'
## This class uploads a file to s3 with public-read access and return the public url
class AwsUploader
# s3 obj after initializing the aws sdk
attr_reader :s3
# initialization requires aws key id, secret, s3 region and s3 bucket data all are env variables
def initialize(key_id, secret, region, bucket)
@aws_key_id = key_id
@aws_secret = secret
@aws_region = region
@aws_bucket = bucket
begin
Aws.config.update({
region: @aws_region,
credentials: Aws::Credentials.new(@aws_key_id, @aws_secret)
})
@s3 = Aws::S3::Resource.new(region: @aws_region)
rescue
nil
end
end
# requires file path to be uploaded to s3 and upload path with filename where the file to be uploaded
# returns the public url of the uploaded file otherwise nil
def upload_to_s3(file_with_path, upload_path)
begin
obj = s3.bucket(@aws_bucket).object(upload_path)
obj.upload_file(file_with_path, acl: 'public-read')
return obj.public_url
rescue
nil
end
end
# requires url of the file to be uploaded to s3, file will be downloaded temporarily and then uploaded to s3 and then deleted that file
# returns the public url of the uploaded file otherwise nil
def upload_from_url(file_url, upload_path)
begin
filename = upload_path.split('/').last
File.open(filename, "wb") do |f|
f.write HTTParty.get(file_url).body
end
url = upload_to_s3(filename, upload_path)
File.delete(filename) if File.exist?(filename)
return url
rescue
nil
end
end
# Calling the class
uploader = AwsUploader.new('AWS_KEY_ID', 'AWS_SECRET', 'AWS_S3_REGION', 'AWS_S3_BUCKET')
# calling upload_to_s3 method
url1 = uploader.upload_to_s3("tmp/my_image.jpg", "direct_upload_test/my_image.jpg")
# calling upload_from_url method
url2 = uploader.upload_from_url("https://i0.wp.com/www.sulmanweb.com/wp-content/uploads/2019/09/IMG_9837.jpg", "direct_upload_test/my_image.jpg")
p url1, url2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment