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

Flutter中如何发送符合特定要求的multipart文件类型POST请求

multipart文件POST请求代码调整方案

现有问题

当前实现代码无法匹配服务端要求的multipart请求结构,核心错误有三点:

  • 上传的supportDocuments文件字段缺少filename参数,多数后端的multipart解析逻辑会将无文件名的文件字段判定为非法请求直接拦截
  • processRequestDtoJSON参数被直接放入普通form字段传输,未指定该part的Content-Type为application/json,后端无法将其识别为JSON结构参数
  • 若手动在请求头中硬编码Content-Type: multipart/form-data,会覆盖http库自动生成的带boundary标识的请求头,导致服务端完全无法解析请求体

现有错误代码片段:

multipartFile = http.MultipartFile.fromBytes(
  'supportDocuments', item.files.single.bytes!,
      contentType: MediaType('application', 'pdf'));
      request.files.add(multipartFile);

request.headers.addAll(headers);
request.fields["processRequestDto"] = jsonEncode(docRefDto);

调整后正确实现

按照以下逻辑修改代码即可发送符合要求的请求:

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

// 1. 构造文件上传part,补充必填的filename参数
final pdfFile = http.MultipartFile.fromBytes(
  'supportDocuments',
  item.files.single.bytes!,
  // 优先使用原文件名,无原文件名时自定义带.pdf后缀的文件名即可
  filename: item.files.single.name ?? 'default_support_doc.pdf',
  contentType: MediaType('application', 'pdf')
);
request.files.add(pdfFile);

// 2. 将processRequestDto构造为指定JSON类型的multipart part,不要放入普通fields字段
final dtoPart = http.MultipartFile.fromString(
  'processRequestDto',
  jsonEncode(docRefDto),
  contentType: MediaType('application', 'json')
);
request.files.add(dtoPart);

// 3. 添加请求头,注意不要手动设置Content-Type,由http库自动生成带boundary的multipart请求头
request.headers.addAll(headers);

注意:如果你的headers里提前写死了Content-Type: multipart/form-data,一定要删掉这行配置,否则请求一定会因为缺少boundary分隔符解析失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 11:45:52