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

Flutter中如何通过POST请求将拍摄的图片上传至服务端API

Flutter 图片上传到服务端实现方案

核心实现逻辑

你已经引入了http依赖,直接使用MultipartRequest实现multipart/form-data格式的文件上传即可,这是前后端通用的文件传输格式,和网页端表单上传文件的格式完全一致。

完整代码示例

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

// 上传图片函数,传入你拍照拿到的File对象,返回接口响应结果
Future<http.StreamedResponse> uploadImage(File imageFile, {Map<String, String>? extraParams}) async {
  // 替换为你自己的服务端接口地址
  var uri = Uri.parse("https://你的接口地址/ocr/upload");
  var request = http.MultipartRequest('POST', uri);
  
  // 附加其他文本参数(如果需要的话,不需要就删掉这段)
  if (extraParams != null) {
    request.fields.addAll(extraParams);
  }

  // 添加上传的图片文件,第二个参数"image"是后端接口接收文件的字段名,必须和后端约定一致
  request.files.add(await http.MultipartFile.fromPath(
    'image', 
    imageFile.path,
    // 可选:指定文件类型,部分后端会校验
    contentType: http.MediaType('image', 'jpeg'),
  ));

  // 发送请求
  var response = await request.send();
  return response;
}

和现有拍照逻辑结合的调用示例

import 'package:image_picker/image_picker.dart';

// 你现有的拍照逻辑触发函数
void takePhotoAndUpload() async {
  final ImagePicker picker = ImagePicker();
  // 调用相机拍照
  final XFile? photo = await picker.pickImage(source: ImageSource.camera);
  if (photo != null) {
    // 转成File格式
    File imageFile = File(photo.path);
    // 调用上传函数,可附加额外参数
    var resp = await uploadImage(
      imageFile,
      extraParams: {
        "user_id": "123456",
        "type": "ocr"
      }
    );
    // 处理响应结果
    if (resp.statusCode == 200) {
      // 读取响应内容
      String respStr = await resp.stream.bytesToString();
      // 这里respStr就是服务端返回的OCR识别后的文本内容,你自己做后续处理
      print("识别结果:$respStr");
    } else {
      print("请求失败,状态码:${resp.statusCode}");
    }
  }
}

注意事项

  • 代码中的image字段名必须和后端接口约定的文件接收参数完全一致,否则后端无法正常获取到上传的图片
  • 如果你的服务端接口需要鉴权(比如token),可以给request添加header:request.headers['Authorization'] = 'Bearer 你的token'
  • 安卓端需要在AndroidManifest.xml中添加网络权限,iOS端需要在Info.plist中配置HTTP访问白名单(如果你的接口是HTTP协议的话)

内容的提问来源于stack exchange,提问作者Hax

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:27:00