简体   繁体   中英

How to upload image to s3 with lambda and API gateway

I want to upload an image to s3 with lambda and Api gateway when i submit form how can i do it in python.

currently i am getting this error while i am trying to upload image through PostMan

Could not parse request body into json: Could not parse payload into json: Unexpected character (\'-\' (code 45))

my code currently is

import json
import boto3
import base64

s3 = boto3.client('s3')
def lambda_handler(event, context):
    print(event)
    try:
        if event['httpMethod'] == 'POST' : 
            print(event['body'])
            data = json.loads(event['body'])
            name = data['name']
            image = data['file']
            image = image[image.find(",")+1:]
            dec = base64.b64decode(image + "===")
            s3.put_object(Bucket='', Key="", Body=dec)
            return {'statusCode': 200, 'body': json.dumps({'message': 'successful lambda function call'}), 'headers': {'Access-Control-Allow-Origin': '*'}}
    except Exception as e:
        return{
            'body':json.dumps(e)
        }

You don't need Lambda for this. You can proxy S3 API with API Gateway https://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-s3.html

Doing an upload through API Gateway and Lambda has its limitations: You can not handle large files and there is an execution timeout of 30 seconds as I recall. I would go with creating a presigned url that is requested by the client through API gateway, then use it as the endpoint to put the file.

Something like this will go in your Lambda,

(This is a NodeJs example)

const uploadUrl = S3.getSignedUrl( 'putObject', {
                Bucket: get(aPicture, 'Bucket'),
                Key: get( aPicture, 'Key'),
                Expires: 600,
            })
    callback( null, { url })

(NodeJs) https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getSignedUrl-property

(Python) https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.generate_presigned_url

Ooops it's over engineering.

anyways, it's seems like your are getting error from API-gateway, first check the lambda through "test lambda" using aws console, if it's working fine and getting the response back from lambda then please check with API-gateway side.

i doubt you are using some mapping templates in gateway, AWS uses AWS Velocity templates, which looks like JSON, but it's different. those mapping template at integration request causing this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM