Flutter中如何发送指定格式的Multipart POST请求
Flutter Multipart POST 请求改造方案
使用官方http包即可完成改造,原有字段的键名规则完全不需要调整,改造后和原普通POST请求的服务端解析逻辑完全兼容,同时支持附加文件上传。
核心改造逻辑
- 替换原
http.post为http.MultipartRequest构造Multipart格式请求 - 原body里的所有普通文本字段(含按索引嵌套的教育经历、职业经历数组字段)全部传入
request.fields,键名和原值保持完全一致 - 若资质证书字段为文件类型,使用
http.MultipartFile构造文件字段附加到请求;若为纯文本则直接放入fields即可 - 不要手动设置
Content-Type请求头,MultipartRequest会自动生成带合法boundary的Content-Type,手动设置会导致服务端解析失败 - 发送请求后将流式响应转为普通Response,原有响应处理逻辑无需修改
完整改造代码
首先确保已导入http包,需要传文件时额外导入dart:io:
import 'package:http/http.dart' as http; import 'dart:io'; // 仅上传本地文件时需要导入
请求实现代码:
// 初始化Multipart POST请求 final request = http.MultipartRequest('POST', Uri.parse(url)); // 填充所有普通表单字段,与原普通POST的body字段完全一致 request.fields.addAll({ "name": "name test", "about": about, "education[institute][0]": "ins one", "education[institute][1]": "ins two", "education[degree][0]": "deg one", "education[degree][1]": "deg two", "education[major][0]": "maj one", "education[major][1]": "maj two", "education[year][0]": "year one", "education[year][1]": "year two", "profession[position][0]": "pro one", "profession[position][1]": "pro two", "profession[company][0]": "com one", "profession[company][1]": "com two", "profession[start][0]": "star one", "profession[start][1]": "star two", "profession[end][0]": "end one", "profession[end][1]": "end two", "certification": certificate // 若certification为文件请删除该行,使用下方文件上传逻辑 }); // 资质证书为文件时启用以下代码 /* request.files.add( await http.MultipartFile.fromPath( 'certification', File(certificateLocalPath).path, // 可选配置:自定义文件名、文件类型 // filename: 'qualification_cert.pdf', // contentType: MediaType('application', 'pdf'), ) ); */ // 追加请求头,注意不要手动传入Content-Type request.headers.addAll(headers); // 发送请求并转换为普通响应对象 final streamedResp = await request.send(); final response = await http.Response.fromStream(streamedResp); // 后续response处理逻辑与原http.post完全一致
注意事项
- 原请求头中如果存在手动配置的
Content-Type字段必须移除,自动生成的Content-Type会携带随机boundary参数,手动配置会导致boundary缺失,服务端无法解析请求体 - 带索引的嵌套数组字段不需要做结构化转换,直接保留原
字段名[子字段][索引]的键名格式即可,服务端解析结果和原普通POST请求完全一致 - 若证书文件是内存中的字节数据(如从内存生成的图片、PDF),可替换
MultipartFile.fromPath为MultipartFile.fromBytes传入字节数组即可
内容的提问来源于stack exchange,提问作者AK IJ
相关产品推荐
相关产品推荐

