Skip to content

Instantly share code, notes, and snippets.

@SohaibAnwaar
Last active September 30, 2022 11:50
Show Gist options
  • Save SohaibAnwaar/85ecc4b29f2df4b40feef4b8b71415b9 to your computer and use it in GitHub Desktop.
Save SohaibAnwaar/85ecc4b29f2df4b40feef4b8b71415b9 to your computer and use it in GitHub Desktop.
Upload Image to public bucket aws s3
import boto3
from botocore.exceptions import NoCredentialsError
import requests
import mimetypes
import time
import random
AWS_STORAGE_BUCKET_NAME = "*********************"
AWS_S3_ACCESS_KEY_ID = "****************"
AWS_S3_SECRET_ACCESS_KEY = "*******************"
region_name = '*********************'
def upload_file(remote_url):
"""Upload image to the aws, we are using presigned urls and they have a expire time. So when ever you
need a url please call get_resource_url api.
Args:
remote_url (Str): Url of the image
bucket (Str): Bucket Name
Returns:
Str: URl of the image if uploaded sucessfully
"""
# Making s3 client
s3 = boto3.client('s3', aws_access_key_id=AWS_S3_ACCESS_KEY_ID, aws_secret_access_key=AWS_S3_SECRET_ACCESS_KEY, region_name= region_name)
# Making random file name
filename = str(int(time.time())) + "/" + str(int(random.random() * 1000000))
try:
# Getting image from remote url
imageResponse = requests.get(remote_url, stream=True).raw
# Get the content of image
content_type = imageResponse.headers['content-type']
# Getting the extension of the image
filename = filename + "." +remote_url.rsplit(".", 1)[-1]
# Uploading
s3.upload_fileobj(imageResponse, AWS_STORAGE_BUCKET_NAME, filename)
url = f"https://backend-s3-assets.s3.ap-northeast-2.amazonaws.com/{filename}"
print("Upload Successful")
return url
except FileNotFoundError:
print("The file was not found")
return remote_url
except NoCredentialsError:
print("Credentials not available")
return remote_url
url = 'https://img.alicdn.com/imgextra/i2/196993935/O1CN017MMKfT1ewHGMdGhH1_!!196993935.jpg'
uploaded = upload_file(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment