Carga de archivos y gestión de formularios multipart
Acepte archivos de los usuarios mediante el campo de entrada de archivos, previsualícelos en el cliente y procese las cargas multipart en el servidor con validación y seguimiento del progreso.
Carga de archivos y gestión de formularios multipart es una lección gratuita de Next.js 15 Fullstack Web Apps en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Next.js 15 Fullstack Web Apps, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Next.js 15 Fullstack Web Apps incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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
Preguntas frecuentes
¿La lección «Carga de archivos y gestión de formularios multipart» es gratis?
Sí — el texto completo de «Carga de archivos y gestión de formularios multipart» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Next.js 15 Fullstack Web Apps, actualiza a CoddyKit PRO. El curso de Next.js 15 Fullstack Web Apps incluye 4 lecciones en total.
¿Qué aprenderé en «Carga de archivos y gestión de formularios multipart»?
Acepte archivos de los usuarios mediante el campo de entrada de archivos, previsualícelos en el cliente y procese las cargas multipart en el servidor con validación y seguimiento del progreso. Practicas Next.js 15 Fullstack Web Apps con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Next.js 15 Fullstack Web Apps?
No se requiere experiencia previa. Next.js 15 Fullstack Web Apps en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Carga de archivos y gestión de formularios multipart»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Next.js 15 Fullstack Web Apps?
Sí. Cada lección de Next.js 15 Fullstack Web Apps incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Componentes controlados y estado
- Validación de formularios con React Hook Form
- Formularios fullstack con Server Actions
- Carga de archivos y gestión de formularios multipart