LoginSignup
4

More than 5 years have passed since last update.

S3にuploadしたzipファイルのイメージ画像をLambdaで解凍する メモ

extract_image_zip.py

import boto3
import zipfile
import traceback
import os

print('Loading function')

s3 = boto3.resource('s3')
s3_client = boto3.client('s3')

def lambda_handler(event, context):

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']

    try: 
        s3_client.download_file(bucket, key, '/tmp/file.zip')
        print('download')
        zfile = zipfile.ZipFile('/tmp/file.zip')
        namelist = zfile.namelist()
        print(namelist)

        for filename in namelist:
            if not os.path.basename('/tmp/'+filename):
                os.mkdir('/tmp/'+filename)
            else:
                f = open('/tmp/' + str(filename), 'wb')
                data = zfile.read(filename)
                f.write(data)
                f.close()
        for filename in namelist:
            if '.jpg' in filename:
                s3_client.upload_file('/tmp/'+filename, bucket, key + filename)


    except Exception as e:
        print(e)
        print(traceback.format_exc())

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
4