Datei-Uploads und Multipart-Formularverarbeitung
Akzeptieren Sie Dateien über das Dateifeld, zeigen Sie eine Vorschau im Client an und verarbeiten Sie Multipart-Uploads auf dem Server mit Validierung und Fortschrittsanzeige.
Datei-Uploads und Multipart-Formularverarbeitung ist eine kostenlose Next.js 15 Fullstack Web Apps-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Next.js 15 Fullstack Web Apps-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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
Lerne TypeScript mit einem KI-Tutor — kostenlos
Schreibe und führe echten Code in deinem Browser aus, bekomme sofortige Hilfe von einem 24/7 KI-Tutor und setze dein Lernen im Web oder in der App fort.
- Kurse
- 12
- Lektionen
- 48
Häufig gestellte Fragen
Ist die Lektion „Datei-Uploads und Multipart-Formularverarbeitung“ kostenlos?
Ja — der vollständige Text von „Datei-Uploads und Multipart-Formularverarbeitung“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Next.js 15 Fullstack Web Apps-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Datei-Uploads und Multipart-Formularverarbeitung“?
Akzeptieren Sie Dateien über das Dateifeld, zeigen Sie eine Vorschau im Client an und verarbeiten Sie Multipart-Uploads auf dem Server mit Validierung und Fortschrittsanzeige. Du übst Next.js 15 Fullstack Web Apps mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Next.js 15 Fullstack Web Apps zu starten?
Keine Vorkenntnisse erforderlich. Next.js 15 Fullstack Web Apps auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Datei-Uploads und Multipart-Formularverarbeitung“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Next.js 15 Fullstack Web Apps-Lektion Code schreiben und ausführen?
Ja. Jede Next.js 15 Fullstack Web Apps-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Kontrollierte Komponenten und State
- Formularvalidierung mit React Hook Form
- Fullstack-Formulare mit Server Actions
- Datei-Uploads und Multipart-Formularverarbeitung