Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Send an Image to a Flask API to be stored on a server for further use

Tags:

python

flask

I am attempting to send an image to a Flask API. So far, I am using base64 to encode the image to be sent as a string. On the server side, I am receiving that string and decoding it, and attempting to write over a file on the server side. The code runs, but the resulting JPG is not viewable, and it shows "It looks like we don't support this format." I have also attempted saving the file as other photo file formats. It is a jpg that I convert to string so that is why I am saving as jpg.

Here is my client side code:

with open(filename, "rb") as img:
    string = base64.b64encode(img.read())

print(type(string))
print(string)

name = 'John Doe'
EmpID = 1
company = 1

def test():
    api_url = "http://192.168.8.13:5000/register-new?emp_name=%s&company_id=%s&emp_id=%s&user_photo=%s" % (name, company, EmpID, string)
    response = requests.post(url= api_url)
    assert response.status_code == 200

And here is the server side code for receiving the photo.

photo = request.args.get('user_photo')
    photo1 = photo.replace(" ", "")
    f = (base64.b64decode(photo1))
    a = io.BytesIO()
    with open("compare.jpg", "wb") as file:
        file.write(f)
like image 225
dstoner Avatar asked Nov 22 '25 20:11

dstoner


1 Answers

If you really want to upload this as base64 data, I suggest putting this as JSON in the post body, rather than as a GET parameter.

On the client side, open the file like this:

with open(filename, "rb") as img:
    string = base64.b64encode(img.read()).decode('utf-8')

Then in your test function, take that image_data string out of the URL, and use the request.post argument json to pass this across with the correct Content Type. You could consider sending the other variables by adding them to the dictionary passed with this arg:

def test():
    api_url = "http://192.168.8.13:5000/register-new?emp_name=%s&company_id=%s&emp_id=%s" % (name, company, EmpID)
    response = requests.post(url= api_url, json={'user_photo':string})

Then on the backend, grab this with Flask's request.get_json function and initialise the BytesIO object, before writing the data to that, and finally writing to a file:

@app.route('/register-new', methods=['POST'])
def register_new():
    photo = request.get_json()['user_photo']
    
    photo_data = base64.b64decode(photo)
    
    with open("compare.jpg", "wb") as file:
        file.write(photo_data)

With a test image this works correctly, as confirmed by the Linux file command:

$ file compare.jpg
compare.jpg: JPEG image data, baseline, precision 8, 500x750, components 3
like image 77
v25 Avatar answered Nov 24 '25 10:11

v25



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!