如何从flask API接收http.MultipartRequest响应中的图像文件?

问题描述

我编写了一个 Flask API,它可以让图像执行一些操作,然后将图像返回给 Flutter 应用程序。这是我从服务器返回图像的代码

printf

这是将图像发送到 api 的 http 多部分请求,并且图像在服务器上正确接收。但是当服务器用图像响应时,我无法将它恢复到颤振状态。这是代码

@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")

我正在尝试将字节转换为图像,以便可以在我的应用程序中显示它,但出现错误

在解析图像编解码器时引发了以下 _Exception: 例外:无效的图像数据

这是我的构建方法

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;
    });

我也尝试将这些字节写入文件,但出现另一个错误提示文件为空。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)