I have a machine learning model that takes a picture and returns a prediction, I uploaded it to a flask server and tested it on website that I created using HTML and it worked, but when I try to use it with a flutter app I get this error : Unhandled Exception: FormatException: Unexpected character (at character 1) when I try to upload a picture from my application. Also, the statusCode I get is 400 .. These are my codes. Any help would be really appreciated.
This is my python code that I created the flask instance in ( I run it on my cmd when I try to establish a connection using the flutter app)
from flask import Flask, render_template, request, jsonify
import cv2
import numpy as np
import pandas as pd
import tensorflow
from tensorflow import keras
from tensorflow.python.keras import backend as k
app = Flask(__name__)
model = tensorflow.keras.models.load_model('model.h5')
@app.route('/')
def index():
return render_template("index.html", data="hey")
@app.route("/prediction", methods=["POST"])
def prediction():
img = request.files['img']
img.save("img.jpg")
image = cv2.imread("img.jpg")
image = cv2.resize(image, (224,224))
image = np.reshape(image, (1,224,224,3))
pred = model.predict(image)
pred = pred > 0.5
if(pred):
predd="Malignant"
else:
predd="Benign"
return jsonify({"prediction": predd,})
#this ip is my network's IPv4
#(I connected both my laptop and mobile to this WiFi while establishing the connection)
if __name__ == "__main__":
app.run(debug=False,host='192.168.1.103',port=5000)
And this is the code I used in flutter to establish the connection
sendImageToServer(File imageFile) async {
var stream = new http.ByteStream(imageFile.openRead());
stream.cast();
var length = await imageFile.length();
print(length);
//this ip is my network's IPv4
//(I connected both my laptop and mobile
//to this WiFi while establishing the connection)
var uri = Uri.parse('http://192.168.1.103:5000/prediction');
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename:
basename(imageFile.path));
request.files.add(multipartFile);
request.headers["Content-Type"] = 'multipart/form-data';
var streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
print(response);
final Map<String, dynamic> responseJson =
json.decode(response.toString()) as Map<String, dynamic>;
print(responseJson.toString());
pre = responseJson["prediction"];
print(pre);
setState(() {
prediction = pre;
});
}
Future getImage() async {
final image = await picker.getImage(source: ImageSource.gallery);
sendImageToServer(File(image.path));
setState(() {
fileImage = File(image.path);
sendImageToServer(fileImage);
});
}
Also this is what I get on the cmd when I send the request
192.168.1.108 - - [20/Mar/2021 19:14:39] "←[1m←[31mPOST /prediction HTTP/1.1←[0m" 400 -
Bad Request
I/flutter (20982):The browser (or proxy) sent a request that this server could not understand.
2 I/flutter (20982): ************************************************************ – Jasmin mansi Mar 20 '21 at 19:47