flutter - 如何从烧瓶 API 接收 http.MultipartRequest 响应中的图像文件?
问题描述
我编写了一个烧瓶 API,它要求图像执行一些操作,然后将图像返回给颤振应用程序。这是我从服务器返回图像的代码:
@app.route("/", methods=["POST", "GET"])
def home():
if request.method == "POST":
imagefile = request.files.get("image", "")
image = performSomeOperation(imagefile)
return send_file(image, mimetype="image/gif")
这是将图像发送到 api 的 http 多部分请求,并且图像在服务器上被正确接收。但是当服务器用图像响应时,我无法让它重新振作起来。这是代码
http.MultipartRequest request =
http.MultipartRequest('POST', Uri.parse('http://192.168.8.111:5000/'));
request.files.add(
await http.MultipartFile.fromPath(
'image',
File(widget.imagePath).path,
contentType: MediaType('application', 'jpeg'),
),
);
http.StreamedResponse r = await request.send();
var response = await http.Response.fromStream(r);
Directory appDocDirectory = await getApplicationDocumentsDirectory();
myfile = new File((appDocDirectory.path) + "/abc12345");
if (myfile.existsSync()) myfile.deleteSync();
var ios = myfile.openWrite(mode: FileMode.write);
bytes = response.bodyBytes;
ios.add(bytes);
ios.close();
setState(() {
this.a = 1;
});
我正在尝试将字节转换为图像,以便可以在我的应用程序中显示它,但出现错误
解析图像编解码器时引发以下 _Exception:异常:图像数据无效
这是我的构建方法:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Display the Picture')),
// The image is stored as a file on the device. Use the `Image.file`
// constructor with the given path to display the image.
body: Column(
children: [
Image.file(File(widget.imagePath)),
ElevatedButton(
onPressed: () {
myFunc(context);
},
child: Text("Recognize"),
),
if (a != 0) ...[Image.memory(bytes)]
],
),
);
}
我也尝试将这些字节写入文件,但发生另一个错误,即文件为空。
解决方案
推荐阅读
- python - 如何从数据框的给定图像计算 JKRowling 的 text_reviews_counts 总数?
- loops - XSL 循环未在每个级别正确发生
- amazon-web-services - 几次成功请求后 Hadoop S3 驱动程序 403 错误
- ubuntu - Windows 7 上的 Oracle VM 虚拟机启动错误:lvmetad 尚未激活
- flask - 烧瓶对excel文件的响应给出损坏的excel文件
- r - 如何为大型数据集创建唯一向量
- java - 如何处理组中的所有已读项目,而不是一对一处理?
- javascript - 如何在javascript中使用多个键进行分组
- python - 熊猫和绘图图
- php - 如何同时运行两个 foreach 循环(laravel)