0Pricing
Next.js 15 Fullstack Web Apps · Aula

Envio de arquivos e tratamento de formulários multipart

Aceite arquivos dos usuários com a entrada de arquivo, faça uma prévia no cliente e processe envios multipart no servidor com validação e acompanhamento do progresso.

Envio de arquivos e tratamento de formulários multipart é uma aula grátis de Next.js 15 Fullstack Web Apps no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Next.js 15 Fullstack Web Apps, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Next.js 15 Fullstack Web Apps inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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.type against allowed MIME types
  • Check file.size against 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 FileList with name, size, type
  • Preview with createObjectURL and 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

Perguntas Frequentes

A aula “Envio de arquivos e tratamento de formulários multipart” é grátis?

Sim — o texto completo de “Envio de arquivos e tratamento de formulários multipart” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Next.js 15 Fullstack Web Apps, atualize para CoddyKit PRO. O curso de Next.js 15 Fullstack Web Apps inclui 4 aulas no total.

O que vou aprender em “Envio de arquivos e tratamento de formulários multipart”?

Aceite arquivos dos usuários com a entrada de arquivo, faça uma prévia no cliente e processe envios multipart no servidor com validação e acompanhamento do progresso. Você pratica Next.js 15 Fullstack Web Apps com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Next.js 15 Fullstack Web Apps?

Nenhuma experiência prévia é necessária. Next.js 15 Fullstack Web Apps no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Envio de arquivos e tratamento de formulários multipart”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Next.js 15 Fullstack Web Apps?

Sim. Cada aula de Next.js 15 Fullstack Web Apps inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Componentes Controlados e Estado
  2. Validação de Formulários com React Hook Form
  3. Formulários Fullstack com Ações de Servidor
  4. Envio de arquivos e tratamento de formulários multipart
← Voltar para Next.js 15 Fullstack Web Apps