Jkennedy559
Jkennedy559

Reputation: 133

How to receive an image from a POST request on Google Cloud Function with Python?

I'm struggling to reassemble an image sent via a POST request to a GCP Cloud Function.

I've looked at advice here about how to package a file with POST request.

I would like the function to reconstruct the image from bytes for further processing, everytime I send the request I get 'Failure' back. Any help would be really appreciated!

### client_side.py
import requests

url = 'https://region-project.cloudfunctions.net/function' # Generic GCP functions URL
files = {'file': ('my_image.jpg', open('my_image.jpg', 'rb').read(), 'application/octet-stream')}
r = requests.post(url, files=files)

### gcp_function.py
from io import BytesIO

def handler(request):
    try:
        incoming = request.files.get('file')
        bytes = BytesIO(incoming)
        image = open_image(bytes)
        message = 'Success'
    except:
        message = 'Failure'
    return message

Upvotes: 0

Views: 1033

Answers (1)

Jkennedy559
Jkennedy559

Reputation: 133

Sorted it.

Needed the read method to convert FileStorage Object to bytes.

### gcp_function.py
from io import BytesIO
import logging

def handler(request):
    try:
        incoming = request.files['file'].read()
        bytes = BytesIO(incoming)
        image = open_image(bytes)
        message = 'Success'
    except Exception as e:
        message = 'Failure'
        logging.critical(str(e))
    return message

Upvotes: 1

Related Questions