[英]How to upload file to folder in aws S3 bucket using python boto3
[英]How I will get response of success in aws file upload on s3 bucket using boto3?
我知道如何使用 boto3 将文件上传到 s3 存储桶上。 但是我已经使用了我的功能,我想检查图像是否已成功上传到 s3 存储桶,如果已上传,则我想执行操作。
所以这里是这样的例子,
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
所以我的要求是直截了当的,如果我成功上传文件,那么我将返回 s3 url 作为响应。 所以请帮助我,你的帮助将不胜感激。
该upload_file()
函数没有返回值。
如果上传有问题,会抛出异常。
例如,如果找不到要上传的本地文件,则会引发FileNotFoundError
异常。 (试一试!)
或者,您可以使用put_object()
返回一个字典:
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
结果将包含这些键:
'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': '...'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.