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

Flutter中如何通过MultipartRequest向API上传含图片的对象数组?

使用 MultipartRequest 上传对象数组的实现方案

Multipart 请求不直接支持嵌套 JSON 结构,你需要将嵌套的数组字段按后端可解析的规则拆分为独立的 Multipart 字段,绝大多数主流服务端框架(Spring Boot、Express、Django 等)都默认支持带索引的字段命名规则,按照如下方式实现即可:

  • 普通文本字段直接按字段名添加:title、owner 直接作为 Multipart 字段名赋值
  • files 数组的每个 image 文件按 files[索引].image 的格式命名,比如第一个文件字段名为 files[0].image,第二个为 files[1].image,以此类推

Dart/Flutter 实现示例

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

Future<void> uploadFiles(List<http.MultipartFile> imageList, String title, int ownerId) async {
  final request = http.MultipartRequest('POST', Uri.parse('替换为你的API接口地址'));
  // 添加上下文文本字段
  request.fields['title'] = title;
  request.fields['owner'] = ownerId.toString();
  // 遍历添加图片数组
  for (int i = 0; i < imageList.length; i++) {
    request.files.add(
      http.MultipartFile(
        'files[$i].image',
        imageList[i].readStream,
        imageList[i].length,
        filename: imageList[i].filename,
      )
    );
  }
  // 发送请求处理响应
  final response = await request.send();
  if (response.statusCode == 200) {
    print('上传成功');
  } else {
    print('上传失败,状态码:${response.statusCode}');
  }
}

JavaScript 实现示例(axios)

import axios from 'axios';

async function uploadFiles(imageList, title, ownerId) {
  const formData = new FormData();
  // 添加上下文文本字段
  formData.append('title', title);
  formData.append('owner', ownerId);
  // 遍历添加图片数组
  imageList.forEach((file, index) => {
    formData.append(`files[${index}].image`, file);
  });
  // 发送请求
  const res = await axios.post('替换为你的API接口地址', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
  console.log('上传成功', res.data);
}

注意事项

  • 如果你的服务端有特殊的序列化规则,比如要求使用 files[][image] 格式的字段名,只需调整字段名拼接规则即可,核心逻辑都是为每个数组元素的文件单独指定带标识的字段名
  • 不要将整个 files 数组转为 JSON 字符串塞到单个 Multipart 字段中,这种方式会导致服务端无法读取二进制文件流,也不符合 Multipart 请求的设计规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:54:01