Home > database >  upload base64 encode image to lambda function
upload base64 encode image to lambda function

Time:12-07

I want to upload upload base64 encoded image to lambda function from postman.

{
  "name": "vendor"
  "image": "base64-enoceded"
}

Lambda Function

    
    try:
        data = json.loads(event['body'])
        name = data['name']
        image = data['image']
        image  = base64.b64decode(data['image'])
        cdn_object = CDNConnector('bunny_cdn_api_key','assets')
        cdn_object.upload_file('vendor-assets/', image)
        return {
            'statusCode': 200,
            "body": json.dumps("File uploaded")
        }
    except Exception as e:
        return {
            "statusCode":200,
            "body": str(e)
        }

But I got this error 'embedded null byte' when I show the file after decoded string, It shows class bytes. But the I want the actual file after decoding i.e. images.png after decoding that I will upload to CDN because CDN required file not bytes.

CodePudding user response:

The API expects a file path, not the raw bytes. You have two options here:

  1. In a Lambda function, you're allowed to write up to 512 Mb to /tmp. Open a binary file in /tmp, write your data here, and then use that file path for the upload.

     with open('/tmp/image.png', 'wb') as fout:
         fout.write(image)
     cdn_object.upload_file('vendor-assets/', '/tmp/image.png')
    
  2. If I've found the API correctly, all that upload_file is doing is reading the entire file into memory and then issuing a PUT with that data. You could do this yourself and skip the wrapper function that requires you to write the data to the file first.

  • Related