AWS S3 Pre-Sign URL 全部 S3 目錄所有檔案都要,我該如何做?

閱讀時間約 4 分鐘


以下為簡單範例,可自行發揮~

建立 Lambda

raw-image

增加 S3 權限

raw-image

為了方便用 s3 full access policy(依照實際情況調整)

raw-image

修改Timeout 時間,依照實際情況調整

raw-image


範例

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) # 格式化输出
}


執行

raw-image


{
"bucket_name": "you bucke",
"prefix": "you prefix/",
"expiration": 3600
}

產生結果

raw-image


raw-image


14會員
59內容數
留言0
查看全部
發表第一個留言支持創作者!