FormData Collects Fields And Files For Posts
Gather text fields, repeated keys, and File values into one FormData, then inspect every entry — file names and byte sizes included — before sending.
Code
// FormData 是表单序列化的统一出口:文本、重复键、文件都进同一个容器
const form = new FormData();
form.set('title', 'Release 2.4');
form.set('channel', 'stable');
form.append('tag', 'release');
form.append('tag', 'q4'); // append 重复键成为多值,set 会覆盖
form.set('changelog', new File(['perf: warm cache'], 'changelog.txt', { type: 'text/plain' }));
// 发送前先检查载荷:File 值带文件名与字节长度
for (const [key, value] of form.entries()) {
const shown = value instanceof File ? 'File ' + value.name + ' (' + value.size + ' bytes)' : value;
console.log(key, '=>', shown);
}
console.log('has channel?', form.has('channel'), '| has csrf?', form.has('csrf'));
// 同一份 entries 也能摊平成普通对象,用于日志或手动编码
const fields = Object.fromEntries(
[...form.entries()].map(([k, v]) => [k, v instanceof File ? v.name : v]),
);
console.log('plain fields:', fields);Output
Captured from a sandboxed run of this snippet in the build pipeline.
title => Release 2.4
channel => stable
tag => release
tag => q4
changelog => File changelog.txt (16 bytes)
has channel? true | has csrf? false
plain fields: {
title: 'Release 2.4',
channel: 'stable',
tag: 'q4',
changelog: 'changelog.txt'
}How the snippet works
One loop does the cycling here: for (const [key, value] of form.entries()).
Top-level bindings form, fields hold the demo state — nothing sits inside a function scope.
Applying it
The demo output is labeled (has channel?, plain fields:), so every printed line maps back to its originating operation.
Statements that matter
const shown = value instanceof File ? 'File ' + value.name + ' (' + value.size + ' bytes)' : value;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `form`, `fields`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.