Issue in uploading image for prediction using a MultiPart POST Request


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

Flutter Code

var request = http.MultipartRequest(
    Map<String, String> headers = {"Content-type": "multipart/form-data"};
        filename: widget.selectedImage.path.split('/').last,
    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

def upload_image():
    if request.method == "POST":
        imageFile = request.files['image']
        fileName = werkzeug.utils.secure_filename(imageFile.filename)
        print('\nRecieved File name : ' + imageFile.filename)'./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.


So, I figured it out by myself.

I will be attaching the code below for future references.

Flutter Code :

var request = http.MultipartRequest(
     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 :

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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published