Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send image file to AWS Lambda Function

I'm trying to send one image to my Lambda Function using Python just to test for one project, but Postman is giving me one error and I don't know how to solve it.

My code is simply to detect if I have some data in the key "image" and return some message. I'm using Postman to send the POST request, I clicked in the Body tab, selected the form-data option and I wrote image for the key and selected the image file from my computer (the image size is 27 kb). This is the code in my Lambda Function:

def lambda_handler(event, context):
    if event['image']:
        return {
            "Message": 'Everything went ok'
        }

And this is the error message that I'm receiving from Postman:

{ "message": "Could not parse request body into json: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value\n at [Source: (byte[])"----------------------------137965576541301454606184\r\nContent-Disposition: form-data; name="image"; filename="TestImage.png"\r\nContent-Type: image/png\r\n\r\n�PNG\r\n\n ... }

like image 279
Jancer Lima Avatar asked Oct 27 '25 07:10

Jancer Lima


2 Answers

To solve that problem, I needed to set my Camera to convert the image to base64 and then upload it to the server.

In the server, I convert it again and then work with it as I want. Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.

So, you will convert your image to string and then sending it, it was the best way that I found to upload my images.

like image 63
Jancer Lima Avatar answered Oct 28 '25 22:10

Jancer Lima


I was struggling with this. I was using Postman, getting UnidentifiedImageError. The below worked.

Posting the Image:

data = open('x.jpg','rb').read()
data = base64.b64encode(data).decode("utf8")
r = requests.post('url',data=data)

Processing on the function side

def lambda_handler(event, context):
image_bytes = event['body'].encode('utf-8')
img_b64dec = base64.b64decode(image_bytes)
img_byteIO = BytesIO(img_b64dec)
image = Image.open(img_byteIO)
like image 44
itsprit Avatar answered Oct 28 '25 21:10

itsprit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!