You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何通过form-data向Web服务发送图片、经纬度等信息?

解决方案:发送图片+地理位置的Form-Data请求

在Flutter中处理这类多类型数据的Form-Data传输,推荐使用Dio库(对multipart请求支持更便捷),也可以用官方的http库,以下是具体实现步骤:

一、修正原代码的Uri定义问题

原代码中Uri uri = 'http://127.0.0.1:5000/analyze';会报错,需要改为:

final Uri uri = Uri.parse('http://127.0.0.1:5000/analyze');

二、使用Dio库实现(推荐)

1. 添加依赖

在pubspec.yaml中加入Dio:

dependencies:
  dio: ^5.4.0  # 可替换为最新版本

执行flutter pub get安装依赖。

2. 实现发送逻辑

在_ConfirmationScreenState中添加发送方法,并绑定到SEND按钮:

import 'package:dio/dio.dart';
import 'package:path/path.dart';

class _ConfirmationScreenState extends State<ConfirmationScreen> {
  Future<void> sendFormData() async {
    // 非空校验,避免空指针
    if (widget.position == null || widget.pictureFile == null) {
      print("图片或位置信息缺失");
      return;
    }

    try {
      final dio = Dio();
      // 构建FormData
      final formData = FormData.fromMap({
        // 地理位置参数
        "latitude": widget.position!.latitude.toString(),
        "longitude": widget.position!.longitude.toString(),
        // 图片文件(根据实际图片类型调整contentType)
        "image": await MultipartFile.fromFile(
          widget.pictureFile!.path,
          filename: basename(widget.pictureFile!.path),
          contentType: MediaType("image", "jpeg"),
        ),
      });

      // 发送POST请求
      final response = await dio.postUri(
        widget.uri,
        data: formData,
      );

      if (response.statusCode == 200) {
        print("数据发送成功");
        // 可添加成功提示(如SnackBar)
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text("发送成功")),
        );
      } else {
        print("请求失败,状态码:${response.statusCode}");
      }
    } catch (e) {
      print("发送异常:$e");
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("发送失败:$e")),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // ... 原build代码不变,仅修改SEND按钮的onPressed
      ElevatedButton(
        style: ElevatedButton.styleFrom(
          primary: Colors.green,
          textStyle: const TextStyle(color: Colors.white)
        ),
        onPressed: sendFormData,
        child: const Text("SEND")
      ),
      // ... 其他代码
    );
  }
}

三、使用官方http库实现(备选)

如果不想引入第三方库,可用Flutter官方http库:

1. 添加依赖

dependencies:
  http: ^1.1.0

2. 发送逻辑实现

import 'package:http/http.dart' as http;
import 'package:path/path.dart';

class _ConfirmationScreenState extends State<ConfirmationScreen> {
  Future<void> sendWithHttp() async {
    if (widget.position == null || widget.pictureFile == null) {
      print("图片或位置信息缺失");
      return;
    }

    try {
      final request = http.MultipartRequest(
        "POST",
        widget.uri,
      );
      // 添加地理位置参数
      request.fields["latitude"] = widget.position!.latitude.toString();
      request.fields["longitude"] = widget.position!.longitude.toString();
      // 添加图片文件
      request.files.add(
        await http.MultipartFile.fromPath(
          "image",
          widget.pictureFile!.path,
          filename: basename(widget.pictureFile!.path),
        ),
      );

      final response = await request.send();
      if (response.statusCode == 200) {
        print("发送成功");
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text("发送成功")),
        );
      } else {
        print("发送失败,状态码:${response.statusCode}");
      }
    } catch (e) {
      print("发送异常:$e");
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("发送失败:$e")),
      );
    }
  }

  // 绑定到SEND按钮的onPressed即可
}

内容的提问来源于stack exchange,提问作者Juan Cruz Alric Cortabarria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:54:23