Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to upload excel file to AWS S3 using an AWS lambda function in python

I have an excel file in generated from a Lamba function, stored in the /tmp/ folder, I want to store it in a S3 bucket, I have setup the permisions and the bucket, but when I complete the function it creates an damaged excel file in the bucket, which cannot be opened.

The code I used:

import boto3

def uploadtoS3(filename=str):
    s3 = boto3.client('s3')
    bucket = 'aws-day-ahead-estimations'
    DirName = '/tmp/' + filename
    s3.put_object(Bucket=bucket,Body=DirName,Key=filename)
    print('put complete')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you use the put_object() method, the Body parameter expects the actual content of the file, not the file path.

You can fix this:

def uploadtoS3(filename=str):
    s3 = boto3.client('s3')
    bucket = 'aws-day-ahead-estimations'
    file_path = '/tmp/' + filename
    try:
        with open(file_path, 'rb') as f:
            s3.put_object(Bucket=bucket, Body=f, Key=filename)
            print('put complete')
    except Exception as e:
        print(f"An error occurred: {e}")

Another approach is to use the upload_file() method of the S3 client instead of the put_object() method.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading