0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This was precisely what I needed, for future endeavors, if I had used the upload_file() method, then the file path would have been sufficient?
Yes file path would have been enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.