首页 > 解决方案 > 如何从烧瓶 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)]
        ],
      ),
    );
  }

我也尝试将这些字节写入文件,但发生另一个错误,即文件为空。

标签: flutterhttpbytesiobytestream

解决方案


推荐阅读