以下為簡單範例,可自行發揮~
建立 Lambda
增加 S3 權限
為了方便用 s3 full access policy(依照實際情況調整)
修改Timeout 時間,依照實際情況調整
範例
import json
import boto3
from botocore.exceptions import NoCredentialsError
def lambda_handler(event, context):
# 初始化 S3 客户端
s3_client = boto3.client('s3')
# 從事件中取得桶名稱和前綴
bucket_name = event.get('bucket_name', 'your-bucket-name')
prefix = event.get('prefix', 'your-directory-prefix/')
expiration = event.get('expiration', 3600)
def generate_presigned_urls(bucket_name, prefix, expiration):
try:
# 列出指定前綴下的所有對象
response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
if 'Contents' not in response:
print("No files found in the specified bucket and prefix.")
return []
urls = []
for obj in response['Contents']:
key = obj['Key']
# 產生預簽名 URL
url = s3_client.generate_presigned_url('get_object',
Params={'Bucket': bucket_name, 'Key': key},
ExpiresIn=expiration)
urls.append({'file': key, 'url': url})
print(f'Generated URL for {key}: {url}')
return urls
except NoCredentialsError:
print("Credentials not available.")
return []
# 呼叫函數產生預簽名 URL
urls = generate_presigned_urls(bucket_name, prefix, expiration)
# 傳回產生的 URL 列表
return {
'statusCode': 200,
'body': json.dumps(urls, indent=4) # 格式化输出
}
執行
{
"bucket_name": "you bucke",
"prefix": "you prefix/",
"expiration": 3600
}
產生結果