简体   繁体   中英

How I will get response of success in aws file upload on s3 bucket using boto3?

I know how to upload the file on the s3 bucket using boto3. But I have used it my function where I want to check like an image is successfully uploaded on the s3 bucket or not and if it is uploaded then I want to perform an action.

So here is the example like,

import boto3

def upload_image_get_url(file_name, bucket, key_name):

   s3 = boto3.client("s3")

   result = s3.upload_file(file_name, bucket, key_name) # Here I got none so How I will check like file is upoaded or not?

   if result == 'success' or result == True:
       response = "https://{0}.s3.us-east-2.amCCazonaws.com/{1}".format(bucket, key_name)
   else:
       response = False

   return response


So my requirement is straight forward like if I got success in file upload then I will return s3 url in response. So please help me and your help will be appreciated.

The upload_file() function does not return a value.

If there is a problem with the upload, an exception will be raised .

For example, if it cannot find the local file to upload, a FileNotFoundError exception will be raised. (Give it a try!)

Alternatively, you can use put_object() that will return a dict:

import os.path
import boto3

def upload_image_get_url(file_name, bucket, key_name):

    s3 = boto3.client("s3")

    # Get the file name
    name = os.path.basename(file_name)

    # Format the key
    s3_key = '{0}/{1}'.format(key_name, name)

    # Send the file
    with open(file_name, 'rb') as fd:
        result = s3.put_object(
            Bucket=bucket,
            Key=s3_key,
            Body=fd
        )

    if result['ResponseMetadata']['HTTPStatusCode'] == 200:
       response = "https://{0}.s3.us-east-2.amCCazonaws.com/{1}".format(bucket, s3_key)
   else:
       response = False

   return response

The result will contains those keys:

'ResponseMetadata':
    'RequestId': '...'
    'HostId': '...'
    'HTTPStatusCode': 200
    'HTTPHeaders':
        'x-amz-id-2': '...'
        'x-amz-request-id': '...'
        'date': 'Fri, 15 Nov 2019 10:56:15 GMT'
        'x-amz-version-id': '...'
        'x-amz-server-side-encryption': 'AES256'
        'etag': '"..."'
        'content-length': '0'
        'server': 'AmazonS3'
    'RetryAttempts': 0
'ETag': '"..."'
'ServerSideEncryption': 'AES256'
'VersionId': '...'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM