问题原因是在解压缩zip文件时,有些文件夹可能会被遗漏,导致返回的文件不完整。解决方法可以采用以下代码示例:
import os import zipfile import boto3
s3_client = boto3.client('s3')
def lambda_handler(event, context): # Set the S3 bucket and key s3_bucket = 'my-s3-bucket' s3_key = 'path/to/my-zipfile.zip'
# Download the zip file from S3
local_zipfile = '/tmp/my-zipfile.zip'
s3_client.download_file(s3_bucket, s3_key, local_zipfile)
# Extract the files from the zip file
with zipfile.ZipFile(local_zipfile) as zf:
for member in zf.infolist():
# Skip directories
if member.is_dir():
continue
# Extract the file
zf.extract(member, '/tmp')
# Upload the extracted files to S3
for filename in os.listdir('/tmp'):
local_file = os.path.join('/tmp', filename)
s3_object_key = 'path/to/{}/{}'.format('my-zipfile', filename)
s3_client.upload_file(local_file, s3_bucket, s3_object_key)
这段代码会下载zip文件到Lambda的本地环境,然后解压文件并将文件上传到S3 bucket。在为上传的文件构建S3对象键时,我们将zip文件夹名称手动添加到路径中,以确保所有文件都被正确地上传到目录中。
上一篇:Awslambda节点和并发