-1

I have a situation where i need to post image and json data to the database using single API request. when I try to post request without images it works fine. when I try to add images and json together it throws an error as when i send request using postman.

Can anyone suggest what could be the best way to resolve this issue ?

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'file

Server

@app.route("/testresult", methods=["POST"])
def testresult():
    if request.method == "POST":
        file = request.files['file']
        traynumber = request.json['traynumber']
        sample_number = request.json["sample_number"]
        test_started = request.json['test_started']
        test_ended= request.json['test_ended']
        resultstatus = request.json['resultstatus']
        traydetails = Traydetails.query.filter(Traydetails.traynumber ==traynumber).first_or_404()
        trayid = traydetails.id
        sampleimage = file.read()
        add_sampleresult = Sampletestresult(trayid,sample_number,test_started,test_ended,resultstatus,sampleimage)
        db.session.add(add_sampleresult)
        db.session.commit()
        return file.filename

Client :

enter image description here

import requests
url = 'http://localhost:5000/testresult'
ig = r'C:\Users\Admin\Pictures\test\cat.jpg'
files = {'file': open(ig, 'rb')}
payload = {"traynumber":"868032cd60444cfca6558ce575c13c0a_1","sample_number":1,"test_started":"2021-06-24 15:30:20","test_ended": "2021-06-24 16:30:20","resultstatus": 1}
value = requests.post(url,files=files,json=payload,verify=False,)
print(value.content)

1 Answers1

1

As far as I can tell, you cannot have due to the encoding type. What you can do however, is convert your image into base64 (example in Python, example in JS), and include the base64 included image data in your JSON.

{
    "traynumber":"868032cd60444cfca6558ce575c13c0a_1",
    "sample_number":1,
    "test_started":"2021-06-24 15:30:20",
    "test_ended": "2021-06-24 16:30:20",
    "resultstatus": 1,

    "image_data": "iVBORw0KGg ...your base64 encoded image"
}
tituszban
  • 4,797
  • 2
  • 19
  • 30
  • if I store in base64 does it affect the performance ? can i store base64 in bytea column in db ? – Manoj Selvam Jun 28 '21 at 14:35
  • The overhead of converting to base64 should be minimal. You should be able to store the base64 data directly in your DB, and only decode it if you have to display it. – tituszban Jun 28 '21 at 14:38