flutter - 如何将图片从我的 Flutter 应用程序发送到 Flask 服务器实例?
问题描述
所以我有一个机器学习模型,它可以拍照并返回一个预测,我将它上传到一个烧瓶服务器并尝试使用我使用 HTML 创建的示例网站对其进行测试,并且它可以工作,但是当我尝试使用它时会颤抖应用程序它不起作用..这些是我的代码。当我尝试从我的应用程序上传图片时,我也在调试控制台中收到此错误
[错误:flutter/lib/ui/ui_dart_state.cc(186)] 未处理的异常:错误状态:平台不允许不安全的 HTTP:http: //192.168.1.103 :5000/prediction
任何帮助将非常感激。
这是我创建烧瓶实例的python代码(当我尝试使用flutter应用程序建立连接时,我在我的cmd上运行它)
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)
这是我在颤振中用来建立连接的代码
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);
var response = await request.send();
var result = await response.stream.bytesToString();
final Map<String, dynamic> responseJson =
json.decode(result.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);
});
}
解决方案
根据您收到的错误,如果将 http 更改为 https 不起作用,请尝试以下操作:
在您android/app/src/main/AndroidManifest.xml
添加以下内容:
<application android:usesCleartextTraffic="true">
</application>
推荐阅读
- mongodb - MongoDB聚合函数
- nginx - 我也想在 EC2 上使用 nodejs 应用程序托管一个静态网站
- python - 从 config.ini 中的另一个部分访问部分键值
- haskell - 在 IO 中作用于谓词的惯用 Haskell 方式是什么?
- asp.net-core - 如何重新启动 Windows 服务中托管的 Kestrel?
- swift - 我可以在同一个控制器中写入和读取 NFS 标记吗
- gcc - 性能报告中的源列显示一些 [未知]
- xpath - 在 text() 中最多选择第二个空格/前两个单词
- javascript - 如何使用 useContext 防止组件中不必要的渲染?
- tabulator - 有没有办法回退到内置格式化程序?