Class MultipartFormData
multipart/form-data 请求体构造器,按 RFC 7578 规范拼装 body,随机生成 boundary。
public sealed class MultipartFormData
- Inheritance
-
MultipartFormData
- Inherited Members
Remarks
典型用法(小~中等文件):
var form = new MultipartFormData();
form.AddText("userId", "42");
form.AddFile("avatar", "photo.jpg", fileBytes, "image/jpeg");
await client.PostMultipartAsync(url, form);
大文件场景用 AddFile(string, string, Stream, long, string)
提交 Stream,配合 BuildStream() 和 ContentLength
走流式上传,避免全量读入内存。HasStreamParts 为 true 时
PostMultipartAsync(IHttpClient, string, MultipartFormData, CancellationToken) 会自动路由到 BodyStream 通路。
ContentType 在实例构造时即可读,包含随机生成的 boundary。
冻结语义:首次调用 Build() 或 BuildStream() 后, form 进入 frozen 状态,再调 AddText(string, string)/AddFile(string, string, byte[], string)/ AddFile(string, string, Stream, long, string) 抛 InvalidOperationException。 Build/BuildStream 本身可重复调用(产出一致)。
Constructors
Properties
- ContentLength
完整 body 的字节长度(boundary + headers + bodies + closing)。不会读取任何 Stream, 只累加预算值,可在不消耗数据的前提下作为
Content-Length提交。
- ContentType
Content-Type header 值,含 boundary。构造时即可读,不依赖 Build()/BuildStream()。
- HasStreamParts
当前 form 里是否存在 Stream part;有则必须走 BuildStream()。
Methods
- AddFile(string, string, byte[], string)
添加内存中的文件字段。
- AddFile(string, string, Stream, long, string)
添加流式文件字段。用于大文件避免全量读入内存;必须给
length以便提前算出Content-Length。Stream 生命周期归调用方,本类不会 Dispose。
- AddText(string, string)
添加文本字段。value 用 UTF-8 编码。
- Build()
构造完整 multipart body。所有 part 必须是内存数据;含 Stream part 时请改用 BuildStream()。
- BuildStream()
返回按需产出 multipart body 的只读 Stream。Stream part 的数据按调用
Read时从源 Stream 拉取,整个 body 不会一次性进内存。配合 BodyStream 使用,设 BodyLength = ContentLength。