2

I have a very basic Flask API which works with a DNN model.

Python backend is like this:

from flask import request
from flask import jsonify
from flask import Flask
import io

app = Flask(__name__)

@app.route("/predict", methods=["POST"])
def predict():
    response = {"success": False}
    if request.method == "POST":
        if request.files.get("image"):
            image = request.files["image"].read()
            image = Image.open(io.BytesIO(image))

            #...
            response = {"success": True}
        else:
            print('Wrong file')
    else:
        print('Wrong method')
    return jsonify(response)

Simplified JavaScript frontend:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
<body>
    <input id="image_selector" type="file">
    <button id="predict_button">Predict</button>
    <p style="font-weight: bold;">Predictions</p>
    <p>Prediction: <span id="prediction_text"></span></p>
    <img id="selected-image" src="">

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        let base64Image
        var fd = new FormData();

        $('#image_selector').change(function() {
            let reader = new FileReader()
            reader.onload = function(e) {
                let dataURL = reader.result
                $('#selected-image').attr("src", dataURL)
                base64Image = dataURL.replace("data:image/jpeg;base64,", "")
                console.log(base64Image)
            }
            fd.append('file', $('#image_selector')[0].files[0])
            reader.readAsDataURL($('#image_selector')[0].files[0])
            $('#prediction_text').text("")
        })

        $('#predict_button').click(function(event) {
            let message = {
                image: base64Image
            }
            console.log(message)

            $.ajax({
                url: "http://localhost:5000/predict",
                type: 'POST',
                data:fd,
                contentType: false,
                processData: false,
                success: function (response) {
                    if (response.error) {
                    $('#prediction_text').text('ERROR')
                    }
                    else {
                        $('#prediction_text').text(response.prediction)
                    }
                    console.log(response)
                },
                error: function () {
                },
            });
        })
    </script>
</body>
</html>

When I try to post an image file, in the Flask app the image couldn't pass the second if and prints "Wrong file" Since this cURL command works just fine: curl -X POST -F image=@001.jpg 'http://127.0.0.1:5000/predict' I guess there is a problem with the file format but I am not sure what it is.

Abdullah Akçam
  • 299
  • 4
  • 18

2 Answers2

0

try request.files["image"] or request.files['file'] instead of request.files.get("image")

for better implementation, check Upload image in Flask

hack3r-0m
  • 700
  • 6
  • 20
0
fd.append('file', $('#image_selector')[0].files[0])

Here changing the "file" to "image" solved the issue. I didn't know names actually matter in this case.

fd.append('image', $('#image_selector')[0].files[0])
Abdullah Akçam
  • 299
  • 4
  • 18