Bootstrap 5 によるファイルアップロードの実装
Bootstrap のファイル入力、ボタン、アラート、進捗表示のスタイルを使い、単一ファイルのアップロードフォームを作成します。この例では最大 5 MiB の JPEG、PNG、PDF を受け付けます。アップロードの完了待ちの間は再送信を防ぎ、サーバーの応答を待ってから受理を報告します。
Bootstrap は表示を担います。選択と転送は JavaScript が処理し、小規模な Node.js の受信サーバーがリクエストを検証します。作成するファイルは public/index.html、public/upload.js、server.ts の三つです。受信サーバーはファイルサイズと SHA-256 チェックサムを報告した後、ファイルを破棄します。アップロードされたファイルは保存しません。
Bootstrap 5 環境のセットアップ
Node.js 26 と最新のブラウザーを使用します。この例は Linux 上の Node.js 26.8.1、26.5.0、および Chromium 152 でテストしました。Bootstrap の公式クイックスタートに掲載されている Bootstrap 5.3.8 の CSS と、対応する整合性ハッシュを使用します。これらのコンポーネントに Bootstrap の JavaScript バンドルは不要です。スタイルシートの読み込みにはインターネット接続が必要ですが、サーバーにサードパーティーパッケージは不要です。
Bash 互換のターミナルで、新しいプロジェクトを作成します。
mkdir bootstrap-upload &&
cd bootstrap-upload &&
printf '%s\n' '{"type":"module"}' > package.json &&
mkdir public
生成された package.json により、server.ts で ES modules が有効になります。ディレクトリがすでに存在する場合や移動に失敗した場合、コマンドの連鎖は停止します。その場合は別のディレクトリ名を選び、既存のプロジェクトを上書きしないでください。サーバーを起動する前に、この新しいプロジェクト内に以下の三つのファイルを作成します。
シンプルなファイルアップロードフォームの作成
以下のドキュメント全体を public/index.html として保存します。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap file upload</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB"
crossorigin="anonymous"
/>
<script src="/upload.js" defer></script>
</head>
<body>
<main class="container py-4">
<div class="row justify-content-center">
<section class="col-12 col-md-8 col-lg-6" aria-labelledby="title">
<h1 id="title" class="h3">Upload a file</h1>
<p>This local demo checks your upload and discards it.</p>
<form id="uploadForm" aria-label="File upload" action="/upload"
method="post" enctype="multipart/form-data" novalidate>
<fieldset id="controls">
<legend class="visually-hidden">Select and upload one file</legend>
<div id="dropZone" class="border rounded p-3 mb-3">
<label for="formFile" class="form-label">Choose a file</label>
<input id="formFile" name="file" class="form-control" type="file"
accept="image/jpeg,image/png,application/pdf" required
aria-describedby="fileHelp errorMessage" />
<p id="fileHelp" class="form-text mb-0">
Drop one file here or use the file picker. JPEG, PNG, or PDF;
nonempty files up to 5 MiB (5,242,880 bytes).
</p>
</div>
<div class="d-grid d-sm-flex mb-3">
<button class="btn btn-primary" type="submit">Upload</button>
</div>
</fieldset>
<div id="errorMessage" class="alert alert-danger" role="alert" hidden></div>
<div id="progress" class="progress mb-2" role="progressbar"
aria-label="Upload transfer" aria-valuemin="0" aria-valuemax="100"
aria-valuenow="0" hidden>
<div id="progressFill" class="progress-bar"></div>
</div>
<p id="status" class="text-break" role="status" aria-atomic="true">
No file selected.
</p>
</form>
</section>
</div>
</main>
</body>
</html>
ラベル付きで表示される Bootstrap のファイル入力は、ブラウザー標準のキーボード操作によるファイル選択を維持します。ドロップ操作は、ファイルを選択するための追加の手段です。カラムは小さな画面では幅いっぱいに広がり、大きな画面では幅が狭まります。d-grid d-sm-flex により、スマートフォンでは Upload ボタンが全幅になります。
赤い枠線だけではエラーの内容を説明できません。スクリプトでは .is-invalid と aria-invalid に加え、aria-describedby で参照する可視のアラートを組み合わせます。フォームは novalidate を使い、これらのメッセージで送信を一貫して処理します。Bootstrap の検証に関するドキュメントでは、アクセシビリティの確保を独自の検証スタイルやツールチップだけに頼らないよう注意しています。
ドラッグ&ドロップ、検証、進捗表示の追加
スクリプト全体を public/upload.js として保存します。選択時と送信時には同じ検証を行います。無効な選択の場合は入力をクリアし、同じファイルを再び選んだときに改めて検証されるようにします。リクエスト中は fieldset を無効にし、イベントハンドラーが追加の送信とドロップを拒否します。リクエストに失敗しても、選択したファイルは再試行のために保持されます。
const form = document.getElementById('uploadForm')
const controls = document.getElementById('controls')
const input = document.getElementById('formFile')
const dropZone = document.getElementById('dropZone')
const errorMessage = document.getElementById('errorMessage')
const status = document.getElementById('status')
const progress = document.getElementById('progress')
const progressFill = document.getElementById('progressFill')
const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf']
const maxSize = 5 * 1024 * 1024
let busy = false
let activeFiles = null
function clearFeedback() {
errorMessage.hidden = true
errorMessage.textContent = ''
input.classList.remove('is-invalid')
input.removeAttribute('aria-invalid')
status.textContent = ''
progress.hidden = true
}
function showError(message, invalid = false) {
errorMessage.textContent = message
errorMessage.hidden = false
input.classList.toggle('is-invalid', invalid)
if (invalid) input.setAttribute('aria-invalid', 'true')
}
function validateSelection() {
clearFeedback()
const file = input.files[0]
let message = ''
if (input.files.length !== 1) message = 'Please select exactly one file.'
else if (!allowedTypes.includes(file.type)) message = 'Choose a JPEG, PNG, or PDF file.'
else if (file.size === 0 || file.size > maxSize) {
message = 'Choose a nonempty file no larger than 5 MiB.'
}
if (message) {
input.value = ''
showError(message, true)
return false
}
status.textContent = `Selected: ${file.name}`
return true
}
input.addEventListener('change', () => {
if (busy) {
input.files = activeFiles
return
}
validateSelection()
})
dropZone.addEventListener('dragover', (event) => {
event.preventDefault()
if (!busy) dropZone.classList.add('border-primary', 'bg-body-tertiary')
})
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('border-primary', 'bg-body-tertiary')
})
dropZone.addEventListener('drop', (event) => {
event.preventDefault()
dropZone.classList.remove('border-primary', 'bg-body-tertiary')
if (busy) return
const files = event.dataTransfer?.files
if (!files || files.length !== 1) {
clearFeedback()
input.value = ''
showError('Please drop exactly one file.', true)
return
}
input.files = files
validateSelection()
})
function setProgress(percent) {
progress.setAttribute('aria-valuenow', String(percent))
progressFill.style.width = `${percent}%`
}
form.addEventListener('submit', (event) => {
event.preventDefault()
if (busy) return
if (!validateSelection()) {
input.focus()
return
}
// Disabled controls are omitted from FormData, so capture the body first.
const body = new FormData(form)
const file = input.files[0]
activeFiles = input.files
busy = true
controls.disabled = true
progress.hidden = false
setProgress(0)
status.textContent = 'Uploading…'
const xhr = new XMLHttpRequest()
function finish(message, failed) {
busy = false
controls.disabled = false
activeFiles = null
if (failed) {
progress.hidden = true
status.textContent = ''
showError(message)
return
}
setProgress(100)
status.textContent = message
form.reset()
}
xhr.upload.addEventListener('progress', (event) => {
if (!event.lengthComputable || event.total === 0) {
progress.removeAttribute('aria-valuenow')
status.textContent = 'Uploading; transfer size unknown…'
return
}
const percent = Math.floor((event.loaded / event.total) * 100)
setProgress(percent)
status.textContent = `${percent}% transferred. Waiting for the server…`
})
xhr.upload.addEventListener('load', () => {
setProgress(100)
status.textContent = '100% transferred. Waiting for the server…'
})
xhr.addEventListener('load', () => {
const reply = xhr.response
if (xhr.status !== 200) {
const message = xhr.status === 413
? 'The server rejected the upload size.'
: `The server rejected the upload (HTTP ${xhr.status}).`
finish(message, true)
return
}
if (!reply || reply.bytes !== file.size || typeof reply.sha256 !== 'string'
|| !/^[a-f0-9]{64}$/.test(reply.sha256)) {
finish('The server returned an unexpected receipt. Acceptance is unconfirmed.', true)
return
}
finish(`Accepted: ${file.name} (${reply.bytes.toLocaleString()} bytes). `
+ `SHA-256: ${reply.sha256}. The demo did not save the file.`, false)
})
xhr.addEventListener('error', () => {
finish('Network error. Acceptance is unconfirmed; you can retry.', true)
})
xhr.addEventListener('timeout', () => {
finish('No response within 30 seconds. Acceptance is unconfirmed; you can retry.', true)
})
xhr.open('POST', form.action)
xhr.responseType = 'json'
xhr.timeout = 30_000
xhr.send(body)
})
XMLHttpRequest.uploadで転送の進捗を取得します。100% への到達はリクエスト本文の送信完了を意味し、サーバーによるファイルの受理ではありません。ラベル付きの Bootstrap のプログレスバーが数値を公開し、別のステータステキストでこの違いを説明します。小さなファイルをローカルでアップロードすると、すぐに 100% になることがあります。
multipart の Content-Type ヘッダーはブラウザーに任せます。このヘッダーには、FormDataの解析に必要な境界文字列が含まれます。無効化されたフィールドは除外されるため、コントロールを無効にする前に本文を取得します。応答が届かない場合は、30 秒のタイムアウトでフォームを再び操作可能にします。タイムアウトや接続障害だけでは、サーバーがすでにリクエストを処理したかどうかは判断できません。このデモは受信内容を破棄するだけなので安全に再試行できますが、ストレージサービスには独自の再試行ポリシーが必要です。
サーバー側でのファイルアップロード処理
以下を server.ts として、public/ と同じディレクトリに保存します。このサーバーは二つの公開ファイルだけを配信し、バッファーに格納するリクエストのサイズを制限して、Node の組み込み Web APIで multipart データを解析します。追加の 64 KiB は multipart ヘッダー用の余裕です。ファイル自体の上限は 5 MiB のままです。チェックサムを使い、受信したバイト列と元のファイルを独立して比較できます。
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { createServer } from 'node:http'
const maxSize = 5 * 1024 * 1024
const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf']
const publicFiles = new Map([
['/', ['index.html', 'text/html; charset=utf-8']],
['/upload.js', ['upload.js', 'text/javascript; charset=utf-8']],
])
const server = createServer(async (req, res) => {
function reply(status: number, data: object): void {
res.writeHead(status, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(data))
}
try {
const asset = publicFiles.get(req.url ?? '')
if (req.method === 'GET' && asset) {
const bytes = await readFile(new URL(`./public/${asset[0]}`, import.meta.url))
res.writeHead(200, { 'Content-Type': asset[1] })
res.end(bytes)
return
}
if (req.method !== 'POST' || req.url !== '/upload') {
reply(404, { error: 'Not found.' })
return
}
const chunks: Buffer[] = []
let size = 0
for await (const chunk of req) {
size += chunk.length
if (size > maxSize + 64 * 1024) {
reply(413, { error: 'Request too large.' })
return
}
chunks.push(chunk)
}
const body = new Response(Buffer.concat(chunks), {
headers: { 'Content-Type': req.headers['content-type'] ?? '' },
})
const data = await body.formData().catch(() => null)
const file = data?.get('file')
if (!data || [...data].length !== 1 || !(file instanceof File)) {
reply(400, { error: 'Send exactly one file field named file.' })
return
}
if (!allowedTypes.includes(file.type)) {
reply(415, { error: 'Unsupported declared file type.' })
return
}
if (file.size === 0 || file.size > maxSize) {
reply(413, { error: 'File must be nonempty and at most 5 MiB.' })
return
}
const sha256 = createHash('sha256')
.update(Buffer.from(await file.arrayBuffer()))
.digest('hex')
reply(200, { bytes: file.size, sha256 })
} catch {
reply(500, { error: 'Unable to handle the request.' })
}
})
server.listen(0, '127.0.0.1', () => {
const address = server.address()
if (address && typeof address !== 'string') {
console.log(`Open http://127.0.0.1:${address.port}`)
}
})
bootstrap-upload 内で、次のコマンドを実行して起動します。
node server.ts
出力された URL を開きます。この URL は利用可能なポートを使用します。index.html を直接開かないでください。フォームと受信サーバーは、サーバーのオリジンを共有する必要があります。サーバーを停止するには Ctrl+C を押します。アップロードしたファイルは保持されないため、同じファイルを再びアップロードしてもディスク上のファイルは置き換わりません。
フォームの動作確認
キーボードで小さな PDF を選択し、Upload を実行します。結果には「Accepted」と表示され、受信バイト数と SHA-256 に続いて「The demo did not save the file.」が表示されるはずです。枠線で囲まれたグループ内にファイルをドロップすることもできます。ウィンドウのサイズを変えて、モバイル向けの縦並びレイアウトを確認してください。
空のファイル、テキストファイル、二つのファイルのドロップ、5 MiB を超えるファイルを試します。いずれもリクエストを送信せずに、説明が画面に表示されるはずです。ファイル名が .pdf で終わっていても、MIME ラベルが空、または想定外の場合は拒否されます。アップロード中はファイル選択と Upload ボタンが無効のままになります。失敗した後は Upload を実行し、同じ選択内容で再試行してください。成功した後は、ファイルを再び選択して次のアップロードを開始します。
ブラウザーの開発者ツールで接続速度を制限すると、進捗を観察しやすくなります。受信サーバーを停止するとネットワークエラーになり、受信サーバーが応答しない場合はタイムアウトのメッセージが表示されます。どちらの場合も、受理されたという表示になってはいけません。ページにスタイルが適用されない場合は、ブラウザーのコンソールでスタイルシートのリクエストと整合性エラーを確認してください。
セキュリティ上の考慮事項
accept 属性と JavaScript の検証は、ユーザーによるファイル選択を補助します。セキュリティ境界ではありません。ブラウザーの File.typeと
multipart ファイルの MIME タイプは、クライアントが提供したメタデータです。受信サーバーは、バイト列が実際に画像や PDF なのかを検査しません。チェックサムが示すのは到着した内容であり、その内容が安全かどうかではありません。
この受信サーバーはローカルテスト用にループバックにバインドし、リクエストをメモリー内にバッファリングします。アップロードサービスとしてデプロイしないでください。ファイルを保持するアプリケーションには、認証と認可を伴うアクセス、リクエスト数と同時実行数の制限、コンテンツ検査、慎重に設計した再試行ポリシーが必要です。アップロードされたファイルは公開静的ディレクトリの外に保存し、利用可能にする前に必要なセキュリティスキャンを実施してください。こうした保存に関する判断にかかわらず、Bootstrap フォームでは本文の送信とサーバーによる受理を区別します。
