ドラッグ&ドロップ対応のカスタム HTML ファイルアップロードボタン
::file-selector-button で標準のファイル入力のボタンを装飾すると、キーボード操作と選択したファイルの表示を維持できます。まず JavaScript なしで動作する単一のマルチパートフォームを作り、次に同じ入力要素へファイルを設定するドロップ領域を追加します。ローカルの受信サーバーで、受信した内容を確認します。
デモ用ファイルの作成
メンテナンス中のリリース系列に属する
24.15.0 以上の最新パッチリリースの Node.js、ブラウザー、Linux、macOS、WSL 上の Bash などの POSIX シェルを用意してください。この例では Node の組み込み API を使うため、パッケージのインストールやコンパイルは不要です。受信サーバーには .mts を使うため、親プロジェクトの package.json にかかわらず、Node は ES モジュールとして実行します。詳しくは Node の TypeScript モジュール規則を参照してください。この手順は Linux 上の Node.js 24.15.0、26.5.0、26.8.1 と Chromium 145、152 でテストしています。
実験用のディレクトリで、次のコマンドを貼り付けて実行してください。
(
mkdir native-upload &&
cd native-upload &&
touch index.html styles.css enhance.js server.mts
)
括弧を使うことで、シェルの作業ディレクトリは元の場所に保たれます。native-upload ディレクトリがすでにある場合、このコマンドはその内容を変更する前に失敗します。失敗した場合は、エラーを解消するか、新しいディレクトリ名を選んでから先に進んでください。以下の例を native-upload 内のファイルに保存してください。任意の JavaScript を追加する手順までは、enhance.js を空のままにします。
標準のファイル入力の維持
このページ全体を native-upload/index.html として保存してください。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Native file upload</title>
<link rel="stylesheet" href="styles.css" />
<script src="enhance.js" defer></script>
</head>
<body>
<main>
<h1>Upload a file</h1>
<form id="upload-form" aria-label="File upload" action="/upload"
method="post" enctype="multipart/form-data">
<section id="drop-area" aria-label="File selection">
<label for="file-input">Choose a file</label>
<p id="file-help">One file, up to 1 MiB. Nothing is saved.</p>
<input id="file-input" name="file" type="file" required
aria-describedby="file-help" />
<p id="drop-hint" hidden>Or drop one file here, then choose Upload.</p>
</section>
<p id="selection-status" role="status" aria-atomic="true"></p>
<button type="submit">Upload</button>
</form>
</main>
</body>
</html>
送信するフォームの中に、ファイル入力がひとつあります。name="file" は受信サーバーが想定するマルチパートのフィールドで、id="file-input" はラベルを関連付けます。required は、ファイル未選択の状態でブラウザーから送信するのを防ぎます。意図的に選択した空のファイルはファイルとして扱われ、この例では許可されます。
入力要素は表示したままにしてください。display: none で非表示にするとキーボード操作の対象から外れます。また、ラベルをボタンのように装飾しても、ボタンとしてのキーボード操作は備わりません。フォーム属性の詳しい説明は、HTML ファイルアップロードフォームのチュートリアルを参照してください。
ボタンとドロップ領域の装飾
次の内容を native-upload/styles.css として保存してください。
:root { color-scheme: light dark; }
:root.dark { color-scheme: dark; }
* { box-sizing: border-box; }
body {
margin: 0;
font: 1rem/1.5 system-ui, sans-serif;
background: Canvas;
color: CanvasText;
}
main { max-width: 36rem; margin: 2rem auto; padding: 1.25rem; }
label { font-weight: 600; }
input[type='file'] { display: block; width: 100%; font: inherit; }
input[type='file']::file-selector-button,
button {
font: inherit;
padding: 0.6rem 0.9rem;
border: 1px solid ButtonText;
border-radius: 0.4rem;
background: ButtonFace;
color: ButtonText;
cursor: pointer;
}
input[type='file']::file-selector-button { margin-inline-end: 0.75rem; }
input:focus-visible,
button:focus-visible { outline: 3px solid Highlight; outline-offset: 4px; }
#drop-area { border: 2px dashed GrayText; padding: 1rem; }
#drop-area.dragover { border-color: Highlight; border-style: solid; }
#selection-status { overflow-wrap: anywhere; }
::file-selector-button 疑似要素は、標準の入力要素内のボタンを装飾します。入力要素のフォントを継承するとは限らないため、フォントを明示的に設定してください。周囲のコントロールには引き続きファイル名が表示され、標準のファイル選択画面を開けます。これらのシステムカラーはブラウザーのライトまたはダークの配色に従います。dark クラスを <html> に指定すると、ダークの配色を明示的に選択します。フォーカスの輪郭線はラベルではなく、実際の入力要素に付きます。破線の領域は別の選択手段なので、追加の Tab 移動先は不要です。
フォームの配信とバイトデータの受信
次の内容を native-upload/server.mts として保存してください。ブラウザー用の 3 ファイルを配信し、file という名前のマルチパートを厳密にひとつだけ、最大 1 MiB まで受け付けます。これとは別に、マルチパート解析前にバッファリングするリクエストボディ全体には、マルチパートのヘッダーと末尾のデータを含めて 2 MiB の上限があります。解析とハッシュ計算には追加のメモリが必要です。これは小規模なローカルデモであり、サーバーの総メモリ使用量を制限するものではありません。
import type { IncomingMessage, ServerResponse } from 'node:http'
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import { parseArgs } from 'node:util'
const { values } = parseArgs({ options: { port: { type: 'string', default: '0' } } })
const port = Number(values.port)
if (!/^\d+$/.test(values.port) || !Number.isInteger(port) || port > 65535) {
throw new Error('Use --port with an integer from 0 to 65535.')
}
const maxFileBytes = 1024 * 1024
const maxRequestBytes = 2 * 1024 * 1024
const assets = new Map<string, { body: Buffer; type: string }>()
for (const [route, file, type] of [
['/', 'index.html', 'text/html; charset=utf-8'],
['/styles.css', 'styles.css', 'text/css; charset=utf-8'],
['/enhance.js', 'enhance.js', 'text/javascript; charset=utf-8'],
]) {
assets.set(route, { body: await readFile(new URL(file, import.meta.url)), type })
}
let origin = ''
function reply(response: ServerResponse, status: number, message: string): void {
response.writeHead(status, {
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
})
response.end(`${message}\n\nNothing was saved. Use Back to return to the form.\n`)
}
async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
if (request.headers.host !== new URL(origin).host) {
request.resume()
reply(response, 403, 'Use the printed loopback URL.')
return
}
const asset = assets.get(request.url ?? '')
if (request.method === 'GET' && asset) {
response.writeHead(200, { 'Content-Type': asset.type })
response.end(asset.body)
return
}
if (request.method === 'GET' && request.url === '/favicon.ico') {
response.writeHead(204).end()
return
}
if (request.method !== 'POST' || request.url !== '/upload') {
request.resume()
reply(response, 404, 'Route not found.')
return
}
if (request.headers.origin !== origin) {
request.resume()
reply(response, 403, 'Submit the form served by this receiver.')
return
}
const chunks: Buffer[] = []
let bytes = 0
// Preserve the connection for readable feedback when stopping the read loop early.
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
if (!Buffer.isBuffer(chunk)) throw new Error('Expected request bytes')
bytes += chunk.length
if (bytes > maxRequestBytes) {
request.resume()
reply(response, 413, 'Request exceeds 2 MiB. Choose a smaller file.')
return
}
chunks.push(chunk)
}
let data: FormData
try {
data = await new Request(origin, {
method: 'POST',
headers: { 'Content-Type': request.headers['content-type'] ?? '' },
body: Buffer.concat(chunks),
}).formData()
} catch {
reply(response, 400, 'Could not read the multipart form.')
return
}
const file = data.get('file')
if ([...data.keys()].length !== 1 || !(file instanceof File) || file.name === '') {
reply(response, 400, 'Choose exactly one file in the file field.')
return
}
if (file.size > maxFileBytes) {
reply(response, 413, 'File exceeds 1 MiB. Choose a smaller file.')
return
}
const receipt = {
name: file.name,
bytes: file.size,
sha256: createHash('sha256').update(new Uint8Array(await file.arrayBuffer())).digest('hex'),
}
reply(response, 200, `Received one file.\n${JSON.stringify(receipt, null, 2)}`)
}
const server = createServer((request, response) => {
void handle(request, response).catch(() => {
console.error('Upload handler failed.')
if (!response.headersSent) reply(response, 500, 'Could not process the upload.')
else response.destroy()
})
})
server.requestTimeout = 30000
server.on('error', () => {
console.error('Could not start the receiver. Check that the port is available.')
process.exitCode = 1
})
server.listen(port, '127.0.0.1', () => {
const address = server.address()
if (!address || typeof address === 'string') throw new Error('Missing TCP address')
origin = `http://127.0.0.1:${address.port}`
console.log(`Open ${origin}/`)
})
サーバーは小さなリクエストをバッファリングし、Node の Request.formData() で解析します。ストリームの destroyOnReturn: false オプションにより、上限を超えたボディのバッファリングを停止しつつ、HTTP 413 レスポンスを返せます。残りのデータは破棄します。ファイルの内容はメモリ内でハッシュ化し、ディスクには一切書き込みません。
JavaScript なしでのフォームの実行
native-upload があるディレクトリから、受信サーバーを起動してください。
node native-upload/server.mts
ターミナルに表示された URL をそのまま開いてください。サーバーは 127.0.0.1 上の空きポートを選びます。index.html を直接開いても、/upload はサーバーにつながりません。終了時は Ctrl+C で停止してください。ブラウザー用のファイルは起動時に読み込まれるため、編集後は再起動してください。固定ポートが必要な場合は、同じコマンドの末尾に --port 8123 を追加します。ポートが使用中の場合は、ゼロ以外の終了ステータスで失敗します。
JavaScript を無効にしてページを再読み込みし、Tab キーで
Choose a file というラベルの入力要素へ移動してください。輪郭線が表示されるはずです。Space キーでファイル選択画面を開いて小さなファイルを選び、Tab キーで Upload へ移動して Enter キーを押します。ブラウザーが /upload へ移動し、Received one file. とともに、ファイル名、バイト数、SHA-256 ハッシュが表示されます。このレスポンスは受信の確認であり、ファイル選択画面のファイル名は選択の確認です。ブラウザーの「戻る」で戻ってください。再送信すると、保存せずにファイルを再び調べます。
送信方法を変えずにドラッグ&ドロップを追加
この任意の拡張機能を native-upload/enhance.js として保存し、受信サーバーを再起動して、JavaScript を有効にした状態で再読み込みしてください。
const form = document.getElementById('upload-form')
const input = document.getElementById('file-input')
const area = document.getElementById('drop-area')
const status = document.getElementById('selection-status')
const hint = document.getElementById('drop-hint')
const maxFileBytes = 1024 * 1024
function checkSelection(files) {
const file = files[0]
if (files.length !== 1 || !file) {
input.value = ''
status.textContent = 'Choose exactly one file.'
return false
}
if (file.size > maxFileBytes) {
input.value = ''
status.textContent = 'File exceeds 1 MiB. Choose a smaller file.'
return false
}
status.textContent = `Selected: ${file.name}. Choose Upload to send it.`
return true
}
input.addEventListener('change', () => checkSelection(input.files))
form.addEventListener('submit', (event) => {
if (!checkSelection(input.files)) event.preventDefault()
})
area.addEventListener('dragover', (event) => {
event.preventDefault()
area.classList.add('dragover')
})
area.addEventListener('dragleave', () => area.classList.remove('dragover'))
area.addEventListener('drop', (event) => {
event.preventDefault()
area.classList.remove('dragover')
if (!event.dataTransfer || !checkSelection(event.dataTransfer.files)) return
try {
input.files = event.dataTransfer.files
} catch {
input.value = ''
status.textContent = 'Could not select this drop. Use the file picker.'
}
})
hint.hidden = false
dataTransfer.filesは
drop ハンドラー内で読み取ります。その FileList を input.files に代入すると、HTML 標準の規定どおり、標準の入力要素の選択内容が変わります。入力要素の value をファイルシステムのパスに変更しても、ファイルは選択できません。
通常のファイルをドロップすると、選択だけが行われます。ステータスにはファイル名と Choose Upload to send it. が表示されます。Upload を選ぶと、同じマルチパートフォームを送信します。別のファイルを選ぶと、最初のファイルが置き換わります。サイズ上限を超えたファイルや複数のファイルをドロップすると、前の選択をクリアし、再選択を促します。ドロップしたファイルの代入に失敗した場合は、標準のファイル選択画面を使ってください。フォルダーはこの例の対象外です。
ここでは fetch() や XHR による送信は行いません。JavaScript が有効でも無効でも、有効な送信にはブラウザーのページ遷移を使います。進捗表示、再試行、ページ遷移のないインターフェースが必要な場合は、カスタム JavaScript アップローダーのチュートリアルを参照してください。
フォームの応用前に拒否動作を確認
ファイル未選択のまま送信してみてください。ブラウザーがファイルの選択を求めるはずです。JavaScript が有効な場合、1 MiB を超えるファイルを選ぶと選択がクリアされ、File exceeds 1 MiB. Choose a smaller file. が表示されます。JavaScript を無効にし、そのファイルをもう一度送信してください。受信サーバーが HTTP 413 で拒否するはずです。ブラウザーの「戻る」で戻り、小さなファイルを選ぶと続行できます。選択した 0 バイトのファイルは、bytes: 0 で成功します。
受信サーバーは、ファイルフィールドの欠落、重複、名前の相違も HTTP 400 で拒否します。不正な形式のマルチパートボディは HTTP 400、バッファ上限の 2 MiB を超えるリクエストは HTTP 413 で拒否します。HTTP 403 は、リクエストのホストまたはオリジンが表示された URL と一致しなかったことを意味します。フォームと受信サーバーは、どちらもその URL 上で使用してください。
このローカル受信サーバーは、どのファイル形式も受け付け、すべてのアップロードを破棄します。ファイルが画像や文書であることや、安全に処理できることは検証しません。accept 属性でファイル選択の候補を絞り込めますが、内容は検証できません。このフォームを公開サービスにつなぐ前に、そのサービスの認証付きアップロードエンドポイントと、サーバー側のサイズおよび内容の検証を使用してください。入力要素のフィールド名は、受信サーバーが想定するフィールド名と一致させてください。
