チャンク分割と並列アップロードによるオンラインファイルアップロードの最適化
チャンクを並列にアップロードするには、各チャンクに固定の位置を割り当て、受信側で全体の結果を検証してからファイルを公開します。ここでは両側を構築します。ブラウザーはチャンクを3つずつ送信し、ローカルの Node.js サーバーは結合済みファイルの SHA-256 ダイジェストを検証した後、ダウンロードできるようにします。
小さく再現性のあるアップロードの選択
この例は、チャンクの並列アップロードの仕組みを学ぶ開発者向けです。Node.js 24.15.0 またはそれ以降の保守対象リリースと、最新の Chromium ブラウザーを使用してください。この例は Linux 上の Node.js 24.15.0 と Chromium 145 でテストしています。Node.js 24 は LTS リリースです。パッケージのインストールは不要です。
このページでは、空ではない 8 MiB 以下の JPEG、PNG、PDF を受け付けます。この小さな上限は意図的なものです。受信側はファイルをメモリに保存し、ブラウザーはストリーミング入力を受け付けない
crypto.subtle.digest()でファイル全体をハッシュ化するためです。これはローカルでプロトコルを学ぶための例であり、大容量ファイルのストレージサービスではありません。サーバーを再起動すると、すべてのファイルが失われます。ページを再読み込みすると、クライアントのアップロード状態が失われます。
各チャンクへの位置の割り当て
256 KiB のチャンクを使用し、0 から番号を付けます。524,295 バイトのファイルは、262,144 バイトが2つ、7 バイトが1つの、3つのチャンクになります。Blob.slice(start, end)は終了位置を含めないため、隣接するスライスが重なったり、隙間が空いたりすることはありません。
このプロトコルには5つの操作があります。
POST /uploadsはファイルサイズと SHA-256 ダイジェストを予約し、サーバーで生成した ID を返します。PUT /uploads/:id/:indexは生のチャンクを番号に対応する位置に書き込みます。同一内容の再試行は成功しますが、受け付け済みの位置に異なる本文を送ると HTTP 409 で失敗します。POST /uploads/:id/completeはすべての位置が存在し、ファイル全体のダイジェストが一致することを検証します。この操作を繰り返しても、同じダイジェストが返ります。GET /uploads/:id/fileは完了後にのみバイト列を返します。ブラウザーもこのバイト列を検証します。DELETE /uploads/:idは完了済みファイルも含めてアップロードを削除します。
ファイルの順序は到着順では決まりません。確認応答が失われるとリクエストが重複する場合があるため、チャンクの書き込みと完了処理は冪等でなければなりません。作成は自動で再試行しません。作成応答が失われると不明な ID が残り、最終的にサーバー側で有効期限が切れます。
ページの作成
新しい空のディレクトリを作成し、次の3つのファイルを同じディレクトリに保存してください。最初のファイルは index.html として保存します。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
<title>Parallel chunk upload</title>
</head>
<body>
<main>
<h1>Parallel chunk upload</h1>
<label for="file">JPEG, PNG, or PDF, up to 8 MiB</label>
<input id="file" type="file" accept="image/jpeg,image/png,application/pdf" />
<button id="upload" type="button">Upload</button>
<button id="cancel" type="button" disabled>Cancel</button>
<p id="status" role="status">Choose a file.</p>
<a id="download" hidden download="upload.bin">Download verified file</a>
</main>
<script type="module" src="/client.js"></script>
</body>
</html>
チャンクの受信と公開
これを server.mts として保存してください。拡張子 .mts により、CommonJS プロジェクト内でも ES モジュールになります。サーバーは Node の
stripTypeScriptTypes()を使い、次のファイルを JavaScript として配信します。Node.js 24.15.0 では、この API は実験的機能の警告を出します。
完了済みも含め、同時に存在できるアップロードは4つです。リクエストがまだ届いていても、各アップロードは作成から 60 秒後に有効期限が切れます。同時に処理できるリクエストは6つで、それぞれに 10 秒の期限があります。セッションデータを検索する前に受信本文を読み取るため、保留中の本文によって削除済みセッションが存続したり、後からそのセッションに書き込まれたりすることはありません。
import { createHash, randomUUID } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { stripTypeScriptTypes } from 'node:module'
const CHUNK_SIZE = 256 * 1024
const MAX_FILE_SIZE = 8 * 1024 * 1024
const MAX_UPLOADS = 4
const MAX_REQUESTS = 6
const TTL_MS = 60_000
type Upload = {
bytes: Buffer
digest: string
seen: Set<number>
complete: boolean
expires: number
}
const uploads = new Map<string, Upload>()
class HttpError extends Error {
status: number
constructor(status: number, message: string) {
super(message)
this.status = status
}
}
function expire(): void {
for (const [id, upload] of uploads) {
if (upload.expires <= Date.now()) uploads.delete(id)
}
}
async function readBody(req: IncomingMessage, limit: number): Promise<Buffer> {
const bytes = Buffer.alloc(limit)
let length = 0
// Leave the socket open long enough to send a useful error response.
for await (const part of req.iterator({ destroyOnReturn: false })) {
if (!Buffer.isBuffer(part)) throw new HttpError(400, 'Expected bytes')
if (length + part.length > limit) throw new HttpError(413, 'Body too large')
part.copy(bytes, length)
length += part.length
}
return bytes.subarray(0, length)
}
async function main(): Promise<void> {
const html = await readFile(new URL('./index.html', import.meta.url))
const client = stripTypeScriptTypes(
await readFile(new URL('./client.ts', import.meta.url), 'utf8'),
)
const port = Number(process.argv[2] ?? 0)
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('Invalid port')
let origin = ''
let active = 0
async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
if (req.headers.host !== new URL(origin).host ||
(req.headers.origin !== undefined && req.headers.origin !== origin)) {
throw new HttpError(403, 'Use the printed local URL')
}
const method = req.method
if (method !== 'GET' && req.headers['x-upload-demo'] !== '1') {
throw new HttpError(403, 'Missing demo header')
}
const path = new URL(req.url ?? '/', origin).pathname
const body = await readBody(req, method === 'PUT' ? CHUNK_SIZE : 0)
expire()
res.setHeader('Cache-Control', 'no-store')
res.setHeader('X-Content-Type-Options', 'nosniff')
if (method === 'GET' && (path === '/' || path === '/client.js')) {
res.setHeader('Content-Type', path === '/' ? 'text/html; charset=utf-8' : 'text/javascript')
res.end(path === '/' ? html : client)
return
}
if (method === 'POST' && path === '/uploads') {
const length = req.headers['upload-length']
const digest = req.headers['upload-sha256']
const size = Number(length)
if (typeof length !== 'string' || !/^[1-9]\d*$/.test(length) ||
!Number.isSafeInteger(size) || size > MAX_FILE_SIZE) {
throw new HttpError(400, 'File must be between 1 byte and 8 MiB')
}
if (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest)) {
throw new HttpError(400, 'Expected a SHA-256 digest')
}
if (uploads.size >= MAX_UPLOADS) throw new HttpError(503, 'Upload capacity reached')
const id = randomUUID()
uploads.set(id, {
bytes: Buffer.alloc(size), digest, seen: new Set(), complete: false,
expires: Date.now() + TTL_MS,
})
res.writeHead(201).end(id)
return
}
const match = /^\/uploads\/([a-f0-9-]{36})(?:\/(\d+|complete|file))?$/.exec(path)
if (!match) throw new HttpError(404, 'Unknown route')
const [, id, operation] = match
if (method === 'DELETE' && operation === undefined) {
uploads.delete(id)
res.writeHead(204).end()
return
}
const upload = uploads.get(id)
if (!upload) throw new HttpError(404, 'Upload missing or expired')
const count = Math.ceil(upload.bytes.length / CHUNK_SIZE)
if (method === 'PUT' && operation !== undefined && /^\d+$/.test(operation)) {
const index = Number(operation)
if (!Number.isSafeInteger(index) || index >= count) {
throw new HttpError(400, 'Invalid chunk index')
}
const start = index * CHUNK_SIZE
const target = upload.bytes.subarray(start, Math.min(start + CHUNK_SIZE, upload.bytes.length))
if (body.length !== target.length) throw new HttpError(400, 'Wrong chunk length')
if (upload.seen.has(index)) {
if (!body.equals(target)) throw new HttpError(409, 'Conflicting chunk')
} else {
body.copy(target)
upload.seen.add(index)
}
res.writeHead(204).end()
return
}
if (method === 'POST' && operation === 'complete') {
if (upload.seen.size !== count) throw new HttpError(409, 'Missing chunks')
if (createHash('sha256').update(upload.bytes).digest('hex') !== upload.digest) {
throw new HttpError(422, 'Digest mismatch')
}
upload.complete = true
res.end(upload.digest)
return
}
if (method === 'GET' && operation === 'file') {
if (!upload.complete) throw new HttpError(409, 'Upload is not complete')
res.setHeader('Content-Type', 'application/octet-stream')
res.setHeader('Content-Disposition', 'attachment; filename="upload.bin"')
res.end(upload.bytes)
return
}
throw new HttpError(405, 'Unsupported operation')
}
const server = createServer({ requestTimeout: 10_000, headersTimeout: 10_000 }, (req, res) => {
if (active >= MAX_REQUESTS) {
res.writeHead(503, { Connection: 'close' }).end('Too many requests')
return
}
active++
let handled = false
let closed = false
const deadline = setTimeout(() => { req.destroy(); res.destroy() }, 10_000)
function release(): void {
if (handled && closed) { clearTimeout(deadline); active-- }
}
res.once('close', () => { closed = true; release() })
handle(req, res).catch((error: unknown) => {
const status = error instanceof HttpError ? error.status : 500
const message = error instanceof HttpError ? error.message : 'Request failed'
if (!res.destroyed) res.writeHead(status, { Connection: 'close' }).end(message)
}).finally(() => { handled = true; release() })
})
server.maxConnections = 16
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(port, '127.0.0.1', () => resolve())
})
const address = server.address()
if (!address || typeof address === 'string') throw new Error('Missing server address')
origin = `http://127.0.0.1:${address.port}`
setInterval(expire, 1000).unref()
console.log(`Open ${origin}`)
}
main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : 'Could not start the server')
process.exitCode = 1
})
4つのセッションバッファーの合計は最大 32 MiB です。これとは別に、受け入れたリクエストは、応答が閉じるまで 256 KiB の受信バッファーを保持するか、8 MiB の送信ファイルを参照する場合があります。削除や有効期限切れによって、そのリクエストのスロットが早期に解放されることはありません。これらはアプリケーションのバッファー制限であり、Node の総メモリ使用量やガベージコレクションのタイミングを制限するものではありません。ヘッダーのタイムアウトと接続数の上限によっても、このローカルサーバーの待機接続が制限されます。Node.js HTTP ドキュメントを参照してください。
チャンクの同時送信を最大3つに制限
これを client.ts として保存してください。各バッチは、すべてのリクエストの処理が確定するまで次のバッチを開始しません。そのため、遅いチャンクがあるとバッチ全体が待たされますが、上限を確認しやすく、再試行によって処理中のチャンクリクエスト数が増えることもありません。
const CHUNK_SIZE = 256 * 1024
const MAX_FILE_SIZE = 8 * 1024 * 1024
const CONCURRENCY = 3
const input = document.getElementById('file')
const uploadButton = document.getElementById('upload')
const cancelButton = document.getElementById('cancel')
const status = document.getElementById('status')
const download = document.getElementById('download')
if (!(input instanceof HTMLInputElement) || !(uploadButton instanceof HTMLButtonElement) ||
!(cancelButton instanceof HTMLButtonElement) || !(status instanceof HTMLParagraphElement) ||
!(download instanceof HTMLAnchorElement)) throw new Error('Missing upload controls')
class HttpError extends Error {
status: number
constructor(status: number) { super(`HTTP ${status}`); this.status = status }
}
async function validateFile(file: File): Promise<void> {
if (file.size === 0 || file.size > MAX_FILE_SIZE) throw new Error('Choose a file between 1 byte and 8 MiB.')
const signatures: Record<string, number[]> = {
'image/jpeg': [0xff, 0xd8, 0xff],
'image/png': [0x89, 0x50, 0x4e, 0x47],
'application/pdf': [0x25, 0x50, 0x44, 0x46],
}
const expected = signatures[file.type]
if (!expected) throw new Error('Choose a JPEG, PNG, or PDF.')
const header = new Uint8Array(await file.slice(0, 4).arrayBuffer())
if (!expected.every((byte, index) => header[index] === byte)) throw new Error('Invalid file signature.')
}
async function sha256(blob: Blob): Promise<string> {
const hash = await crypto.subtle.digest('SHA-256', await blob.arrayBuffer())
return Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, '0')).join('')
}
function waitForRetry(ms: number, signal: AbortSignal): Promise<void> {
signal.throwIfAborted()
return new Promise((resolve, reject) => {
const onAbort = () => { clearTimeout(timer); reject(signal.reason) }
const timer = setTimeout(() => {
signal.removeEventListener('abort', onAbort)
resolve()
}, ms)
signal.addEventListener('abort', onAbort, { once: true })
})
}
async function request(
path: string, options: RequestInit, signal: AbortSignal, retry = true,
): Promise<Blob> {
for (let attempt = 0; ; attempt++) {
signal.throwIfAborted()
try {
const response = await fetch(path, {
...options,
signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]),
headers: { ...options.headers, 'X-Upload-Demo': '1' },
})
if (!response.ok) throw new HttpError(response.status)
return await response.blob()
} catch (error) {
signal.throwIfAborted()
if (!retry || attempt === 2 ||
(error instanceof HttpError && ![408, 429, 500, 502, 503, 504].includes(error.status))) {
throw error
}
await waitForRetry(250 * 2 ** attempt, signal)
}
}
}
let running: AbortController | null = null
cancelButton.addEventListener('click', () => running?.abort())
input.addEventListener('change', () => {
if (running) return
download.hidden = true
status.textContent = 'Ready to upload.'
})
uploadButton.addEventListener('click', async () => {
if (running) return
const file = input.files?.[0]
if (!file) { status.textContent = 'Choose a file.'; return }
const controller = new AbortController()
const signal = controller.signal
running = controller
input.disabled = uploadButton.disabled = true
cancelButton.disabled = false
download.hidden = true
let id: string | undefined
let verified = false
try {
status.textContent = 'Checking file…'
await validateFile(file)
const digest = await sha256(file)
signal.throwIfAborted()
// Finish creation so cancellation can learn the ID and delete it.
id = await (await request('/uploads', {
method: 'POST', headers: { 'Upload-Length': String(file.size), 'Upload-SHA256': digest },
}, new AbortController().signal, false)).text()
signal.throwIfAborted()
const count = Math.ceil(file.size / CHUNK_SIZE)
let acknowledged = 0
for (let first = 0; first < count; first += CONCURRENCY) {
signal.throwIfAborted()
const batch = []
for (let index = first; index < Math.min(first + CONCURRENCY, count); index++) {
const chunk = file.slice(index * CHUNK_SIZE, (index + 1) * CHUNK_SIZE)
batch.push(request(`/uploads/${id}/${index}`, { method: 'PUT', body: chunk }, signal).then(() => {
signal.throwIfAborted()
acknowledged += chunk.size
status.textContent = `${Math.round(100 * acknowledged / file.size)}% of bytes acknowledged.`
}))
}
const results = await Promise.allSettled(batch)
const failure = results.find((result) => result.status === 'rejected')
if (failure) throw failure.reason
}
status.textContent = 'All chunks acknowledged. Verifying…'
const confirmation = await request(`/uploads/${id}/complete`, { method: 'POST' }, signal)
if (await confirmation.text() !== digest) throw new Error('Unexpected confirmation.')
const result = await request(`/uploads/${id}/file`, {}, signal)
if (result.size !== file.size || await sha256(result) !== digest) throw new Error('Downloaded bytes differ.')
signal.throwIfAborted()
verified = true
download.href = `/uploads/${id}/file`
download.hidden = false
status.textContent = 'Upload verified. Download is available until the upload expires.'
} catch (error) {
status.textContent = signal.aborted ? 'Upload canceled.' :
`Upload failed: ${error instanceof Error ? error.message : 'Please try again.'}`
} finally {
if (id && !verified) {
try {
await request(`/uploads/${id}`, { method: 'DELETE' }, new AbortController().signal)
} catch {
status.textContent += ' Cleanup could not be confirmed; the server will expire the upload.'
}
}
running = null
input.disabled = uploadButton.disabled = false
cancelButton.disabled = true
}
})
パーセント表示は、短い最後のチャンクも含め、確認応答を受け取ったバイト数を数えます。現在転送中のバイト数を測るものではありません。100% でも成功ではなく、完了処理とその後のダウンロード検証が成功して初めてリンクが表示されます。1つのリクエストでは転送容量を使い切れない場合、並列リクエストを増やすとスループットが向上することがありますが、オーバーヘッドも増えます。実際に使う受信側とネットワークで測定してください。このデモは速度を保証するものではありません。
アップロードの実行と中断
保存した3つのファイルがあるディレクトリで、次を実行してください。
node server.mts
出力された http://127.0.0.1:PORT URL を開いてください。index.html を直接開かないでください。ファイルを選択し、Uploadをクリックします。All chunks acknowledged. Verifying…の後に、Download verified fileリンクが表示されます。この時点で、ページはサーバーのファイルを取得して検証済みです。リンクをクリックすると別のダウンロードが始まり、保存先はブラウザーが制御します。サーバーは常に、ダウンロードファイル名として upload.bin を提示します。
処理中はファイル入力とアップロードボタンが無効になります。Cancelをクリックすると、リクエストと再試行の待機を中止します。キャンセルが認識される前に、作成処理とローカルでのハッシュ計算が終了します。その後、クリーンアップ処理が既知の ID の削除を試みます。クリーンアップ処理が確定するまで、コントロールは無効のままです。クリーンアップの失敗や作成応答の消失により、有効期限までデータが残る場合があります。リクエストのキャンセルでは、サーバーがすでに処理した完了操作を取り消せないため、クリーンアップでは完了済みアップロードも削除します。
AbortSignal.any() と AbortSignal.timeout()で、ユーザーによるキャンセルと、リクエストの試行ごとの 5 秒のタイムアウトを組み合わせます。ネットワーク障害と、列挙した一時的な HTTP ステータスでは、250 ms と 500 ms の再試行間隔で最大3回試行します。その他の HTTP エラーは直ちに失敗します。これらのブラウザーのタイムアウトはアクティブ時間を使うため、ページの休止中は停止する場合があります。サーバーの処理期限と有効期限は、これとは独立しています。
409 応答は、チャンクの欠落または重複したチャンクの競合を意味します。422 は、結合後のダイジェストが正しくないことを意味します。503 は、完了済みファイルも含めて4つのアップロードスロットがすべて埋まっている場合があります。有効期限が切れるのを待って、やり直してください。存在しない ID や期限切れの ID には 404 が返ります。終了したら Ctrl+C でサーバーを停止してください。空いている特定のポートを使うには、server.mts の後にポート番号を渡します。使用中のポートでは、準備完了の URL を出力せず、エラーで終了します。
ローカル環境との境界の明確化
受信側は 127.0.0.1 にのみバインドし、ホストとブラウザーのオリジンを検証します。変更操作にはカスタムヘッダーを必須とし、指定されたファイル名をパスとして使うことはありません。内容を解釈せず、バイト列を添付ファイルとして配信します。クライアントのシグネチャ検証はファイルの選択ミスを検出するためのものです。先頭部分やダイジェストが一致しても、ファイルが安全である証明にはなりません。受信側は長さ、位置、容量、ダイジェストを独立して検証しますが、画像や PDF の構造検証、マルウェアスキャンは行いません。
このサーバーを公開アップロードサービスとして公開しないでください。デプロイする受信側には、認証、ユーザーごとの認可とクォータ、HTTPS、永続ストレージ、利用側に適したコンテンツ検証が必要です。ここでの ID はローカルのアップロードを分離するためのもので、アカウントの権限システムではありません。
次のステップの選択
チャンク2つ分より少し大きいファイルを試し、ブラウザーのネットワークパネルでリクエストを観察してください。最後のチャンクは小さくなり、ファイルの URL は完了後にのみ利用できるはずです。メモリを永続ストレージに置き換える際も、この境界を維持することが重要です。
再読み込み後に復旧するには、保守されているプロトコルを使用し、受信側の状態と整合させるために十分な状態を永続化してください。tusは、HEAD によるオフセットの確認と、PATCH による再開を定義しています。部分アップロードの並列実行には、オプションの連結拡張を使います。この番号付きチャンクのデモは別のプロトコルであり、tus クライアントではありません。Uppy の tus プラグインは、互換性のある tus サーバー向けに保守されているブラウザークライアントが必要な場合に、実用的な次のステップとなります。
