我看到了其他问题,但这不是我想要的,我不想上传图像到服务器,我不想转换到Base64…

我只想在表单数据或其他东西中发布一个文件,并获取返回的信息.

我有这个,但没有工作:

  void onTakePictureButtonPressed() {
    takePicture().then((String filePath) {
      if (mounted) {
        setState(() {
          imagePath = filePath;
          videoController?.dispose();
          videoController = null;
        });

        http.post('http://ip:8082/composer/predict', headers: {
          "Content-type": "multipart/form-data",
        }, body: {
          "image": filePath,
        }).then((response) {
          print("Response status: ${response.statusCode}");
          print("Response body: ${response.body}");
        });


        if (filePath != null) showInSnackBar('Picture saved to $filePath');
      }
    });
  }

推荐答案

最简单的方法是发布一个类似于this post的多部分请求,然后将其发布到服务器.

确保在文件开头导入以下内容:

import 'package:path/path.dart';
import 'package:async/async.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'dart:convert';

在代码中的某个地方添加此类:

upload(File imageFile) async {    
      // open a bytestream
      var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
      // get file length
      var length = await imageFile.length();

      // string to uri
      var uri = Uri.parse("http://ip:8082/composer/predict");

      // create multipart request
      var request = new http.MultipartRequest("POST", uri);

      // multipart that takes file
      var multipartFile = new http.MultipartFile('file', stream, length,
          filename: basename(imageFile.path));

      // add file to multipart
      request.files.add(multipartFile);

      // send
      var response = await request.send();
      print(response.statusCode);

      // listen for response
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });
    }

然后使用以下方式上传:

upload(File(filePath));

在代码中:

void onTakePictureButtonPressed() {
    takePicture().then((String filePath) {
      if (mounted) {
        setState(() {
          imagePath = filePath;
          videoController?.dispose();
          videoController = null;
        });

       // initiate file upload
       Upload(File(filePath));

        if (filePath != null) showInSnackBar('Picture saved to $filePath');
      }
    });
  }

Flutter相关问答推荐

如何在flater中实现Notch?

当未聚焦且非空时,在flutter中更改文本字段的标签 colored颜色

在Flutter TextField中计算子字符串位置

Flutter AppBar Animation反向调试

我想在Flutter中画一个箭头,但我似乎无法填满空间

顶部对齐ListTile的[前导、标题、尾随]小部件

当 Dart SDK 版本范围不匹配时,为什么依赖解析器不会抛出错误?

自定义类提供程序 Riverpod Flutter 中的可变变量

文本溢出文本框 - Flutter

在我使用 flutter_riverpod stateprovider 重新保存代码之前,UI 主题状态不会更新

Flutter 判断 Uint8List 是否有效 Image

如何从另一个页面访问 Firebase 值?

Flutter/Riverpod 创建复杂对象的副本,其值在某处发生变化

如何从底部导航栏打开 bottomModal 表?

SfCircularChart 周围的额外间距

从物理设备 Flutter 中移除 USB 后启动画面不可见?

如何在 SingleChildScrollView 小部件中管理自定义小部件状态

如何使用 Riverpod 在运行时动态创建提供程序?

Flutter 将方法应用于静态变量

setState 不会在第一次更新 - Flutter