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.

JavascriptForm Validation

Code

javascriptsnippet
20 lines
// 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

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`.