ファイルアップロードとマルチパートフォーム処理
file inputでユーザーからファイルを受け取り、クライアントでプレビューし、サーバーでバリデーションと進捗表示を伴うマルチパートアップロードを処理します。
「ファイルアップロードとマルチパートフォーム処理」はCoddyKit上の無料Next.js 15 Fullstack Web Appsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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
よくある質問
「ファイルアップロードとマルチパートフォーム処理」レッスンは無料ですか?
はい。「ファイルアップロードとマルチパートフォーム処理」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Next.js 15 Fullstack Web Appsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Next.js 15 Fullstack Web Appsコースには全4レッスンが含まれています。
「ファイルアップロードとマルチパートフォーム処理」で何を学びますか?
file inputでユーザーからファイルを受け取り、クライアントでプレビューし、サーバーでバリデーションと進捗表示を伴うマルチパートアップロードを処理します。 ブラウザで直接実行するハンズオンコードでNext.js 15 Fullstack Web Appsを演習し、24時間対応の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によるフォームバリデーション
- Server Actionsによるフルスタックフォーム
- ファイルアップロードとマルチパートフォーム処理