Renzins Pukis
Renzins Pukis

Reputation: 3

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')

Upvotes: 0

Views: 1737

Answers (1)

Taron Qalashyan
Taron Qalashyan

Reputation: 723

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.

Upvotes: 1

Related Questions