6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at
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())

6
4
1

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
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?