文件上传与多部分表单处理
通过文件输入接收用户的文件,在客户端预览文件,并在服务器端对多部分上传进行验证和进度处理。
文件上传与多部分表单处理 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The File Input
Users send files through <input type="file">. Adding multiple allows several files, and accept filters the picker by type.
<input type="file" accept="image/*" multiple />Reading Selected Files
The input exposes a FileList on its files property. Each File carries the name, size, and MIME type.
function onChange(e) {
const file = e.target.files[0];
console.log(file.name, file.size, file.type);
}Client-Side Preview
Generate an instant preview without uploading using URL.createObjectURL, which makes a temporary local URL for the file.
const url = URL.createObjectURL(file);
setPreview(url); // <img src={preview} />Client-Side Validation
Reject bad files before they leave the browser to save bandwidth and give fast feedback:
- Check
file.typeagainst allowed MIME types - Check
file.sizeagainst a max
if (file.size > 5 * 1024 * 1024) {
alert('Max 5 MB');
return;
}What Is multipart/form-data?
Files cannot ride in JSON. The browser encodes them as multipart/form-data: each field becomes a part with its own headers, and binary file content stays intact.
Building FormData
The FormData object assembles a multipart body programmatically. Append fields and files, then send it with fetch — do not set the Content-Type yourself; the browser adds the boundary.
const fd = new FormData();
fd.append('avatar', file);
fd.append('userId', '42');
await fetch('/api/upload', { method: 'POST', body: fd });Handling Uploads in Next.js
A Server Action or route handler reads the multipart body. With the Web API, call request.formData() and pull the file out.
export async function POST(req) {
const form = await req.formData();
const file = form.get('avatar');
const bytes = await file.arrayBuffer();
// save bytes...
return Response.json({ ok: true });
}Server-Side Validation
Never trust the client. Re-validate on the server: confirm the MIME type, enforce the size limit, and sanitize the filename to avoid path traversal before writing to disk or storage.
Storing Files
For production, do not store uploads on the app server filesystem (it is ephemeral). Stream them to object storage such as S3 or a managed blob store, and save only the resulting URL in your database.
Upload Progress
To show a progress bar you need byte-level events, which fetch does not expose for uploads. Use XMLHttpRequest and listen to its upload.onprogress event.
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => {
setPct(Math.round((e.loaded / e.total) * 100));
};
xhr.open('POST', '/api/upload');
xhr.send(fd);Security Checklist
Safe uploads require:
- Allowlist of MIME types and extensions
- Hard size limits enforced server-side
- Randomized, sanitized stored filenames
- Never executing or serving uploads from a trusted path
Quick Check
Test your file-upload knowledge.
Recap
You learned to handle uploads end to end:
- The file input yields a
FileListwith name, size, type - Preview with
createObjectURLand validate on the client - Send a FormData multipart body; read it with
request.formData() - Always re-validate server-side, store in object storage, and follow the security checklist
常见问题解答
「文件上传与多部分表单处理」课时是免费的吗?
是的 — 「文件上传与多部分表单处理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
「文件上传与多部分表单处理」这节课中我会学到什么?
通过文件输入接收用户的文件,在客户端预览文件,并在服务器端对多部分上传进行验证和进度处理。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack Web Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「文件上传与多部分表单处理」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 受控组件与状态
- 使用 React Hook Form 进行表单验证
- 使用服务器操作构建全栈表单
- 文件上传与多部分表单处理