Search code examples
pythonformsflaskfile-upload

want to fetch image from web to backend flask but its showing badrequest key error


I am trying to fetch a single Image from user but has been constantly facing following error werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'file'

following code is written on main.html file


<form action="/predict" method="POST" enctype="multipart/form-data">
        <input type="file" ,name = "file", >
        <button type = 'submit'>Submit </button>
    </form> 

and below here is how I am trying to retrieve the image data

@app.route('/predict',methods=['POST','GET'])
def predict():
       if  request.method== 'POST':
              # image_data = request.form['file1']
              image_data = request.form["file"]
              print(image_data)
              return 'ok'


Solution

  • To access files sent via http request, you must use the files property of the request object:

    change

    image_data = request.form["file"]
    

    to:

    image_data = request.files["file"]