r/awslambda • • Apr 13 '21

uploading and extracting a compressed html file

Hey all, wanting to know if anyone can help me.

I've created a zip of an html file, and I have a (python) Lambda function to extract the zip file archive and place the contents into the S3 bucket.

It's 'sort-of' working, however the html files ends up with metadata Content-Type as binary/octet-stream. So when access the file via URL (it's public), instead of opening the file like an HTML page, it tried to download it.

If I upload the HTML file manually, it works as expected.

Does anybody know what I'm doing wrong. I can post the Lambda function I'm using, but I suspect it's not right anyway (copy/paste from online).

Cheers!!

Edit: figured it out myself. Have posted code as comment for future reference

2 Upvotes

1 comment sorted by

3

u/noknockers Apr 13 '21 edited Apr 13 '21

figured it out. Dumping function here for future reference:

import os
import tempfile
import zipfile
import boto3

s3 = boto3.client('s3')

def lambda_handler(event, context):
    # Parse and prepare required items from event
    global bucket, zipdata
    event = next(iter(event['Records']))
    bucket = event['s3']['bucket']['name']
    key = event['s3']['object']['key']
    dirname = key.split(".")[0]

    # Create temporary file
    temp_file = tempfile.mktemp()

    # Fetch and load target file
    s3.download_file(bucket, key, temp_file)
    zipdata = zipfile.ZipFile(temp_file)

    # itterate internal files and upload 
    for filename in zipdata.namelist():
        extraArgs={}
        
        # force content type on html files
        if ".html" in filename:
            extraArgs={'ContentType': 'text/html'}

        s3.upload_fileobj(
            zipdata.open(filename),
            Bucket=bucket,
            Key=f'{dirname}/{filename}',
            ExtraArgs=extraArgs
        )