Angular での再開可能なファイルアップロード
tus-js-client と tus サーバーを使い、サーバーに保存済みのバイト位置から
Angular のファイルアップロードを再開します。この例では、スタンドアロンの Angular フォームと、ローカルディスクに保存する受信サーバーを構築します。転送を一時停止してページを再読み込みし、同じファイルを選択してアップロードを完了できるようになります。
再開可能なアップロードが必要な理由は?
tus プロトコルでは、POST でアップロード URL を作成し、PATCH リクエストでバイトを送信します。再開時には
HEAD リクエストで保存済みの Upload-Offset を取得します。再開位置はサーバーのオフセットによって決まります。ブラウザーのプログレスバーだけでは、接続が中断した後にどのバイトが残っているかはわかりません。
ブラウザーに保存されるのはアップロード URL であり、ファイルのコピーではありません。再読み込み後は、同じブラウザープロファイルとページのオリジンで、変更していない元のファイルを再び選択する必要があります。サイトストレージの消去、ファイルの変更、サーバーに保存したアップロードの消失により、最初からやり直す場合があります。
Angular プロジェクトのセットアップ
この手順では Node.js 24.22.1 と Yarn 4.12.0 を使用します。以下のパッケージバージョンは、Linux 上の Chromium 145 でビルドと動作を確認しています。Angular には独自のNode.js と TypeScript の互換性要件があります。ここで固定するバージョンは、テスト済みの構成を示しています。
サンプルを配置する作業ディレクトリで、新しいプロジェクトディレクトリを作成します。以下の Bash コマンドは、既存のディレクトリや、外側に Yarn Plug’n’Play プロジェクトがある場合には実行を拒否します。そのローダーが Angular のビルドに影響する可能性があるためです。シェルの作業ディレクトリは元の場所のままです。
(
node --input-type=module <<'NODE' &&
import { existsSync, realpathSync } from 'node:fs'
import { dirname, join } from 'node:path'
let directory = realpathSync('.')
while (true) {
if (existsSync(join(directory, '.pnp.cjs')) || existsSync(join(directory, '.pnp.js'))) {
console.error('Create this demo outside the enclosing Yarn Plug’n’Play project.')
process.exit(1)
}
const parent = dirname(directory)
if (parent === directory) break
directory = parent
}
NODE
mkdir resumable-upload-demo &&
cd resumable-upload-demo &&
printf 'nodeLinker: node-modules\n' > .yarnrc.yml &&
touch yarn.lock
)
以下の各ファイルを resumable-upload-demo 内に保存します。ローカルのロックファイルと Yarn 設定により、この例専用の依存関係をインストールします。package.json は直接依存するパッケージとブラウザーのビルドターゲットを固定します。
{
"name": "resumable-upload-demo",
"private": true,
"type": "module",
"packageManager": "yarn@4.12.0",
"scripts": {
"build": "ng build",
"start": "ng serve --host 127.0.0.1 --port 4200",
"server": "node server.ts"
},
"browserslist": ["Chrome 145"],
"dependencies": {
"@angular/build": "22.2.0",
"@angular/cli": "22.2.0",
"@angular/common": "22.2.0",
"@angular/compiler": "22.2.0",
"@angular/compiler-cli": "22.2.0",
"@angular/core": "22.2.0",
"@angular/platform-browser": "22.2.0",
"@tus/file-store": "2.1.1",
"@tus/server": "2.4.5",
"@types/node": "24.19.0",
"rxjs": "7.8.2",
"tslib": "2.8.1",
"tus-js-client": "4.3.1",
"typescript": "6.0.3"
}
}
angular.json を保存し、ビルドと開発サーバーを
main.ts に接続します。
{
"version": 1,
"cli": { "analytics": false, "cache": { "enabled": false } },
"projects": {
"demo": {
"projectType": "application",
"root": ".",
"architect": {
"build": {
"builder": "@angular/build:application",
"options": {
"browser": "main.ts",
"tsConfig": "tsconfig.json",
"index": "index.html",
"outputPath": "dist",
"styles": [],
"assets": []
}
},
"serve": {
"builder": "@angular/build:dev-server",
"options": { "buildTarget": "demo:build" }
}
}
}
}
}
tsconfig.json を保存します。Node の型はクライアントパッケージの共有型宣言を満たすためのもので、ブラウザーに Node API を追加するものではありません。
{
"compilerOptions": {
"target": "ES2022",
"module": "preserve",
"moduleResolution": "bundler",
"experimentalDecorators": true,
"strict": true,
"types": ["node"],
"lib": ["ES2022", "DOM"],
"rewriteRelativeImportExtensions": true
},
"angularCompilerOptions": { "strictTemplates": true },
"files": ["main.ts"]
}
index.html を保存します。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<base href="/" />
<title>Resumable Angular upload</title>
</head>
<body><app-upload></app-upload></body>
</html>
ローカルの tus サーバーの追加
server.ts を保存します。Node tus サーバーがプロトコルと CORS ヘッダーを処理し、FileStoreがアップロードされたバイトとメタデータを
uploads/ に保存します。同じディレクトリからプロセスを再起動すれば、これらは保持されます。このローカル受信サーバーのファイルサイズ上限は 100 MiB で、認証はありません。ループバックにのみバインドしてください。
import { FileStore } from '@tus/file-store'
import { Server } from '@tus/server'
const server = new Server({
path: '/files',
datastore: new FileStore({ directory: './uploads' }),
maxSize: 100 * 1024 * 1024,
allowedOrigins: ['http://127.0.0.1:4200'],
})
server.listen({ host: '127.0.0.1', port: 1080 })
.once('listening', () => {
console.log('Tus receiver ready at http://127.0.0.1:1080/files')
})
.once('error', () => {
console.error('Cannot start the receiver. Check whether port 1080 is already in use.')
process.exitCode = 1
})
アップロードサービスの作成
upload.service.ts を保存します。このサービスは保存済み URL の検索前に処理中の状態を確保し、停止したアップロードからのコールバックを無視します。また、abort() を待ってから次の開始を許可します。クライアントの非同期コールバックが UI を更新すると、シグナルが Angular に通知します。ゾーンレス変更検知でも同様です。
import { Injectable, signal, type OnDestroy } from '@angular/core'
import { DetailedError, Upload } from 'tus-js-client'
@Injectable()
export class UploadService implements OnDestroy {
readonly busy = signal(false)
readonly pausing = signal(false)
readonly percentage = signal(0)
readonly message = signal('Choose a file, then select Upload.')
readonly uploadUrl = signal<string | null>(null)
#upload: Upload | null = null
#ignoreCallbacks = false
async start(file: File): Promise<void> {
if (this.busy()) return
if (file.size > 100 * 1024 * 1024) {
this.message.set('Choose a file no larger than 100 MiB.')
return
}
this.busy.set(true)
this.#ignoreCallbacks = false
this.percentage.set(0)
this.uploadUrl.set(null)
this.message.set('Uploading…')
const isCurrent = (): boolean => this.#upload === upload && !this.#ignoreCallbacks
const upload = new Upload(file, {
endpoint: 'http://127.0.0.1:1080/files',
chunkSize: 1024 * 1024,
retryDelays: [0, 1000, 3000, 5000],
removeFingerprintOnSuccess: true,
metadata: { filename: file.name },
onUploadUrlAvailable: () => {
if (isCurrent()) this.uploadUrl.set(upload.url)
},
onProgress: (sent, total) => {
if (isCurrent()) this.percentage.set(total > 0 ? (sent / total) * 100 : 0)
},
onSuccess: () => {
if (!isCurrent()) return
this.#upload = null
this.busy.set(false)
this.percentage.set(100)
this.message.set('Upload complete.')
},
onError: (error) => {
if (!isCurrent()) return
this.#upload = null
this.busy.set(false)
const status = error instanceof DetailedError ? error.originalResponse?.getStatus() : null
this.message.set(status === 401 || status === 403
? 'Upload denied. Check authorization before retrying.'
: 'Upload failed. Check the receiver and connection, then select Upload to retry.')
},
})
this.#upload = upload
try {
const previous = await upload.findPreviousUploads()
if (!isCurrent()) return
if (previous[0]) upload.resumeFromPreviousUpload(previous[0])
upload.start()
} catch {
if (!isCurrent()) return
this.#upload = null
this.busy.set(false)
this.message.set('Cannot prepare the upload. Check browser storage, then retry.')
}
}
async pause(): Promise<void> {
const upload = this.#upload
if (!upload || this.pausing()) return
this.#ignoreCallbacks = true
this.pausing.set(true)
try {
await upload.abort()
this.#upload = null
this.busy.set(false)
this.message.set('Paused. Select Upload to resume.')
} catch {
this.message.set('Could not pause. Select Pause to try again.')
} finally {
this.pausing.set(false)
}
}
ngOnDestroy(): void {
const upload = this.#upload
this.#upload = null
void upload?.abort().catch(() => {
console.error('Unable to pause the upload during cleanup.')
})
}
}
クライアント APIでは、abort() は一時停止と定義されています。一方、abort(true) は削除を要求します。この例では停止したクライアントインスタンスを破棄し、次の開始時にその URL を検索します。そのため、ボタンによる再開も再読み込み後の復旧も、ブラウザーへの URL 保存が必要です。保存済みの一致する項目のうち最初のものを選択する方式は、この単一ユーザー向けデモに適しています。
チャンクを 1 MiB にすると、個々のリクエストを調べやすくなります。再開機能に必須ではなく、クライアントのデフォルトではチャンクサイズに上限はありません。再試行ポリシーは連続した再試行の回数を制限し、転送が進むとその回数をリセットします。再試行が停止した後は、Upload からもう一度試せます。
アップロードコンポーネントの構築
main.ts を保存します。これはスタンドアロンコンポーネントであると同時にアプリケーションのエントリーポイントでもあるため、ルートテンプレートやモジュールの追加の接続作業はありません。サービスインスタンスはこのコンポーネントに属し、Angular がコンポーネントを破棄するときにクリーンアップされます。
import { DecimalPipe } from '@angular/common'
import { Component, inject, signal } from '@angular/core'
import { bootstrapApplication } from '@angular/platform-browser'
import { UploadService } from './upload.service.ts'
@Component({
selector: 'app-upload',
standalone: true,
imports: [DecimalPipe],
providers: [UploadService],
template: `
<main>
<h1>Resumable upload</h1>
<label for="file">Choose file</label>
<input id="file" type="file" [disabled]="uploader.busy()" (change)="select($event)" />
<button type="button" (click)="start()" [disabled]="!file() || uploader.busy()">
Upload
</button>
<button type="button" (click)="uploader.pause()"
[disabled]="!uploader.busy() || uploader.pausing()">Pause</button>
<p>Sent: {{ uploader.percentage() | number: '1.0-0' }}%</p>
<progress max="100" [value]="uploader.percentage()" aria-label="Upload progress"></progress>
<p role="status">{{ uploader.message() }}</p>
@if (uploader.uploadUrl(); as url) {
<p>Upload URL: <code>{{ url }}</code></p>
}
</main>
`,
})
export class UploadComponent {
readonly uploader = inject(UploadService)
readonly file = signal<File | null>(null)
select(event: Event): void {
if (this.uploader.busy()) return
if (event.target instanceof HTMLInputElement) {
this.file.set(event.target.files?.[0] ?? null)
}
}
start(): void {
const file = this.file()
if (file) void this.uploader.start(file)
}
}
bootstrapApplication(UploadComponent).catch(() => {
console.error('Unable to start the upload application.')
})
実行と転送再開の検証
七つのファイルをすべて保存したら、親ディレクトリからインストールとビルドを実行します。
(cd resumable-upload-demo && yarn install && yarn build)
ビルドが成功したら、一方のターミナルで受信サーバーを、もう一方で Angular 開発サーバーを起動します。どちらも同じ親ディレクトリから実行してください。
(cd resumable-upload-demo && yarn server)
(cd resumable-upload-demo && yarn start)
http://127.0.0.1:4200 を開きます。Choose file で 100 MiB 未満のファイルを選び、Upload を選択します。数 MiB のファイルとブラウザーのネットワーク帯域制限を使い、Pause を選択する時間を確保します。Paused. Select Upload to resume. が表示されるまで待ってから続けます。
ブラウザーのネットワークリクエストを確認します。PATCH が少なくとも一度成功した後、ページを再読み込みし、変更していない同じファイルを選択して、Upload を再び選択します。以前のアップロード URL への HEAD に続き、PATCH が確認できるはずです。そのリクエストの
Upload-Offset は、HEAD が返したオフセットと一致します。そのオフセットはゼロより大きいはずです。新しい POST があれば、クライアントは以前のアップロードを再開せず、新しいアップロードを作成しています。
Upload complete. が表示されるまで待ちます。表示されたアップロード URL の最後のセグメントは、resumable-upload-demo/uploads/ 内のファイルを識別します。隣接する .json ファイルにはメタデータが入っています。アップロードされたファイルのバイト列または SHA-256 ダイジェストを元のファイルと比較します。元のファイル名はメタデータであり、ディスク上のパスではありません。成功後に再びアップロードすると、クライアントは完了済み URL の記録を削除しているため、別のリソースが作成されます。既存のアップロードはディスク上に残ります。
パーセント表示はブラウザーが送信したバイト数を示し、復旧後には下がる場合があります。完了は tus の成功コールバックで判断します。プログレスバーが 100% に達したかどうかではありません。どちらも、本番アプリケーションによるファイルの検証、セキュリティスキャン、公開が済んだことを意味するものではありません。
CORS 設定
127.0.0.1 を一貫して使用してください。localhost は異なるオリジンです。受信サーバーはポート 4200 の Angular オリジンを許可し、tus のリクエストヘッダーと、ブラウザーに公開するレスポンスヘッダーを提供します。これには Location と Upload-Offset が含まれます。ポートが使用中の場合は別のポートを選び、server.ts、upload.service.ts、または start スクリプト内の対応する URL を更新します。CORS エラーはクライアント側でネットワーク障害として現れることが多いため、アップロードリクエストだけでなくプリフライトレスポンスも確認してください。
CORS は認証ではありません。この受信サーバーはローカルテスト用で、ユーザーを認可しません。tus-js-client は独自の XMLHttpRequest トランスポートを使用するため、Angular の HttpInterceptor はこれらのリクエストに認証情報を付加しません。保護された環境への統合では、クライアントのドキュメントに記載された
headers または onBeforeRequest オプションを使い、追加するヘッダーをサーバーで許可し、すべてのアップロード操作で認可を行ってください。この例には認証情報を含めず、認証情報は信頼できるアップロード URL にのみ送信してください。
ベストプラクティスと考慮事項
クライアントのブラウザーフィンガープリントは、コンテンツのハッシュではなく、ファイルのメタデータとエンドポイントを使用します。変更していない元のファイルを再選択してください。複数アカウントに対応するアプリケーションには、アカウント単位の URL ストレージと、複数の一致候補を扱うための明確なポリシーが必要です。最初の一致候補を選ぶだけでは、所有権の確認にはなりません。
保存済み URL が 404 または 410 を返す場合、バージョン 4.3.1 は、設定されたエンドポイントで新しいアップロードを作成する処理にフォールバックします。サーバーから失われたバイトはブラウザーストレージから復元できません。このローカルサーバーは、有効期限に基づく処理のスケジュールや、放置されたファイルの削除を行いません。作業が終わったら Ctrl+C で両方のプロセスを停止し、データが不要になった場合にのみ、デモの uploads/ ディレクトリを削除してください。
接続障害の場合は、受信サーバーまたはネットワークを復旧してから再試行します。リクエストが拒否された場合は、まず認可の問題を解決します。このフォームは、実行中のアップロードが完了、失敗、または一時停止の処理を完了するまで、ファイル選択と次の開始を無効にします。一時停止に失敗した場合は、ほかの操作を始める前に Pause を再試行してください。サーバーはブラウザーとは独立してサイズ制限を適用します。本番環境のコンテンツ検証とストレージのクリーンアップも、サーバー側で行う必要があります。
