Issue in uploading image for prediction using a MultiPart POST Request

Question:

The call is currently happening via a Flutter application which makes a multi-part POST request.

Flutter Code

var request = http.MultipartRequest(
      'POST',
      Uri.parse('https://techfarmtest.herokuapp.com/upload'),
    );
    Map<String, String> headers = {"Content-type": "multipart/form-data"};
    request.files.add(
      http.MultipartFile(
        widget.selectedImage.toString(),
        widget.selectedImage.readAsBytes().asStream(),
        widget.selectedImage.lengthSync(),
        filename: widget.selectedImage.path.split('/').last,
      ),
    );
    request.headers.addAll(headers);
    var res = await request.send();
    http.Response response = await http.Response.fromStream(res);
    var data = jsonDecode(response.body);
    return data;

I intend to upload the image to the backend and then perform the prediction and retrieve the result in JSON format and the backend is scripted using Flask.

Flask Code

@app.route('/upload',methods=["POST"])
def upload_image():
    if request.method == "POST":
        imageFile = request.files['image']
        fileName = werkzeug.utils.secure_filename(imageFile.filename)
        print('nRecieved File name : ' + imageFile.filename)
        imageFile.save('./uploadedImages/' + fileName)
        pred('./uploadedImages/fileName')
def pred(sampleFile):
    model = load_model('./model.h5')
    # model.summary()
    sample_file = sampleFile
    sample_img = image.load_img(sample_file,target_size = (256,256,3))
    sample_img = image.img_to_array(sample_img)
    sample_img = np.expand_dims(sample_img,axis=0)


    prediction_arr = model.predict(sample_img)
    result = {
        'Sample' : str(sampleFile),
        'Label' : str(class_names[prediction_arr.argmax()]),
        'Confidence' : str(prediction_arr.max())
    }
    return jsonify(result)

The current issue I am facing is that I am making a bad request (400).This is a rough code (pseudocode) that I have figured out from various resources. Is there any way to go about it.

Asked By: Sai Gruheeth

||

Answers:

So, I figured it out by myself.

I will be attaching the code below for future references.

Flutter Code :

var request = http.MultipartRequest(
     'POST',
     Uri.parse('https://techfarmtest.herokuapp.com/upload'),
);
request.files.add(
     await http.MultipartFile.fromPath('image', img.path),
);
var res = await request.send();

You can verify the POST request by using the below logs :

log('${res.statusCode}', name: 'POST-request-statusCode');
log('${res.reasonPhrase}', name: 'POST-request-status');

With respect to Flask :

@app.route('/upload',methods=["POST","PUT"])
def upload_image():
    if request.method == "POST":
        imageFile = request.files['image']
        ***you can perform any operation on the file you have recieved from the request now***

Thank you!

Answered By: Sai Gruheeth