### Quick Start: Upload File with Progress Tracking (TypeScript) Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Demonstrates the basic usage of the ChunkedUploader to upload a file. It shows how to initialize the uploader, call the uploadFile method, and handle progress updates and completion/error states. This example requires a 'file' object to be available. ```typescript import { ChunkedUploader } from 'chunked-uploader-sdk'; const uploader = new ChunkedUploader({ baseUrl: 'https://upload.example.com', apiKey: 'your-api-key', }); // Upload a file with progress tracking const result = await uploader.uploadFile(file, { onProgress: (event) => { console.log(`Progress: ${event.overallProgress.toFixed(1)}%`); }, }); if (result.success) { console.log('Upload complete:', result.finalPath); } else { console.error('Upload failed:', result.error); } ``` -------------------------------- ### Install Chunked Uploader SDK Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Installs the chunked-uploader-sdk package using npm. This is the first step to integrate the SDK into your project. ```bash npm install chunked-uploader-sdk ``` -------------------------------- ### Basic File Upload with ChunkedUploader SDK Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Demonstrates how to initialize the ChunkedUploader and upload a file selected from a browser's file input. It logs the upload result to the console. This basic setup requires a running server at the specified baseUrl and a valid apiKey. ```typescript import { ChunkedUploader } from 'chunked-uploader-sdk'; const uploader = new ChunkedUploader({ baseUrl: 'http://localhost:3000', apiKey: 'your-api-key', }); // Browser: File input const input = document.querySelector('input[type="file"]') as HTMLInputElement; input.addEventListener('change', async () => { const file = input.files?.[0]; if (!file) return; const result = await uploader.uploadFile(file); console.log(result); }); ``` -------------------------------- ### Advanced Manual Chunk Upload Control Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Provides an advanced example of manually controlling the upload process by initializing the upload, uploading each chunk individually using `uploadPart`, and then completing the upload. This method offers the most flexibility over the upload flow. It requires a `File` object and the `uploader` instance. ```typescript async function manualUpload(file: File) { // 1. Initialize const init = await uploader.initUpload(file.name, file.size); const chunkSize = init.chunk_size; // 2. Upload parts manually for (const part of init.parts) { const start = part.part * chunkSize; const end = Math.min(start + chunkSize, file.size); const chunk = file.slice(start, end); const result = await uploader.uploadPart( init.file_id, part.part, part.token, chunk ); console.log(`Part ${result.part_number} uploaded`); } // 3. Complete const complete = await uploader.completeUpload(init.file_id); console.log('File path:', complete.final_path); } ``` -------------------------------- ### High-Concurrency Parallel Uploads Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Explains how to configure the `ChunkedUploader` for high-concurrency uploads, both globally and per-upload, to maximize throughput on fast network connections. It shows an example of uploading a large file with 20 simultaneous part uploads and logging MB uploaded. ```typescript const uploader = new ChunkedUploader({ baseUrl: 'http://localhost:3000', apiKey: 'your-api-key', concurrency: 10, // Default concurrency }); // Override per-upload for even more parallelism const result = await uploader.uploadFile(largeFile, { concurrency: 20, // 20 simultaneous part uploads! onProgress: (event) => { const mbUploaded = (event.uploadedParts * 50).toFixed(0); console.log(`${mbUploaded}MB uploaded (${event.overallProgress.toFixed(1)}%)`); }, }); ``` -------------------------------- ### Get Upload Status (TypeScript) Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Uses the `getStatus` method to retrieve the current progress and status of an ongoing upload, identified by its `uploadId`. It provides details on the percentage complete, number of uploaded parts versus total parts, and the status of individual parts. ```typescript const status = await uploader.getStatus(uploadId); console.log(`Progress: ${status.progress_percent}%`); console.log(`Uploaded: ${status.uploaded_parts}/${status.total_parts}`); // Find pending parts const pending = status.parts.filter(p => p.status === 'pending'); ``` -------------------------------- ### Get Upload Status Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Queries the current upload progress and status. It helps identify which parts of the file have been uploaded and which are still pending. ```APIDOC ## Get Upload Status ### Description Query current upload progress and status to check which parts are pending or completed. ### Method GET ### Endpoint `/upload/status/{upload_id}` (assumed, based on context) ### Parameters #### Path Parameters - **upload_id** (string) - Required - The unique identifier for the upload session. #### Query Parameters None #### Request Body None ### Request Example (TypeScript code example provided in source illustrates usage, not a direct JSON request body) ### Response #### Success Response (200) - **filename** (string) - The name of the file being uploaded. - **total_size** (integer) - The total size of the file in bytes. - **progress_percent** (float) - The overall upload progress as a percentage. - **status** (string) - The current status of the entire upload (e.g., 'in_progress', 'completed', 'failed'). - **uploaded_parts** (integer) - The number of parts successfully uploaded. - **total_parts** (integer) - The total number of parts for the file. - **parts** (array) - An array of objects, each describing the status of a part. - **part** (integer) - The part number. - **status** (string) - The status of the individual part (e.g., 'pending', 'uploaded'). - **checksum_sha256** (string, optional) - The SHA256 checksum if the part is uploaded. #### Response Example ```json { "filename": "my_document.pdf", "total_size": 104857600, "progress_percent": 55.5, "status": "in_progress", "uploaded_parts": 5, "total_parts": 10, "parts": [ { "part": 0, "status": "uploaded", "checksum_sha256": "a1b2c3d4e5f6..." }, { "part": 1, "status": "pending" } ] } ``` ``` -------------------------------- ### Upload Initialization API Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Initializes the upload process on the server. Requires API Key authentication. ```APIDOC ## POST /upload/init ### Description Initializes the upload process on the server. This endpoint is used to start a new file upload and typically returns an upload ID. ### Method POST ### Endpoint /upload/init ### Parameters #### Query Parameters - **apiKey** (string) - Required - The API key for authentication. ### Request Body This endpoint likely does not require a request body for initialization, but may accept metadata if designed to do so. ### Request Example ```json { "fileName": "example.txt", "fileSize": 1024 } ``` ### Response #### Success Response (200) - **uploadId** (string) - The unique identifier for the initiated upload. - **maxChunkSize** (integer) - The maximum allowed size for each chunk in bytes. #### Response Example ```json { "uploadId": "abc123xyz789", "maxChunkSize": 5242880 } ``` ``` -------------------------------- ### Initialize ChunkedUploader Configuration (TypeScript) Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Defines the configuration interface for the ChunkedUploader, including essential parameters like baseUrl and apiKey, as well as optional settings for timeout, concurrency, retry logic, and custom fetch implementation. ```typescript interface ChunkedUploaderConfig { /** Base URL of the chunked upload server */ baseUrl: string; /** API key for management endpoints */ apiKey: string; /** Request timeout in milliseconds (default: 30000) */ timeout?: number; /** Number of concurrent chunk uploads (default: 3) */ concurrency?: number; /** Retry attempts for failed chunks (default: 3) */ retryAttempts?: number; /** Delay between retries in milliseconds (default: 1000) */ retryDelay?: number; /** Custom fetch implementation */ fetch?: typeof fetch; } ``` -------------------------------- ### Initialize Upload Session Manually (TypeScript) Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Shows how to manually initiate an upload session using `initUpload`. This method requires the filename and total size of the file, and optionally accepts a webhook URL. It returns essential information like the upload ID and total number of parts. ```typescript const response = await uploader.initUpload('large-video.mp4', fileSize); console.log(`Upload ID: ${response.file_id}`); console.log(`Parts: ${response.total_parts}`); ``` -------------------------------- ### Cancellable Upload with AbortController Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Demonstrates how to implement user-cancellable uploads using the `AbortController` API, allowing for in-progress uploads to be stopped gracefully. ```APIDOC ## Cancellable Upload with AbortController ### Description Implement user-cancellable uploads using AbortController to stop in-progress uploads. ### Method POST (for `uploadFile`) ### Endpoint `/upload/file` (assumed, based on context) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (File) - Required - The file object to upload. - **options** (object) - Optional - Configuration options for the upload. - **signal** (AbortSignal) - Optional - An `AbortSignal` to cancel the upload. - **onProgress** (function) - Optional - A callback function to receive progress updates. - **event** (object) - **overallProgress** (float) - The overall upload progress percentage. ### Request Example (TypeScript code example provided in source illustrates usage, including event listeners for cancellation and progress) ### Response #### Success Response (200) - **success** (boolean) - Indicates if the upload was successful. - **finalPath** (string) - The server path of the uploaded file if successful. #### Error Response - **message** (string) - Description of the error, potentially 'Upload aborted' if cancelled. #### Response Example ```json { "success": true, "finalPath": "/path/to/uploaded/file.txt" } ``` ``` -------------------------------- ### Node.js File Upload with ChunkedUploader SDK Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Demonstrates how to use the `ChunkedUploader` in a Node.js environment to upload files from the disk. It reads a file into a buffer and uploads it, showing progress on `process.stdout`. This requires the `fs/promises` module. ```typescript import { ChunkedUploader } from 'chunked-uploader-sdk'; import { readFile } from 'fs/promises'; const uploader = new ChunkedUploader({ baseUrl: 'http://localhost:3000', apiKey: 'your-api-key', concurrency: 5, // More concurrent uploads for server-side }); async function uploadFromDisk(filePath: string) { const buffer = await readFile(filePath); const result = await uploader.uploadFile(buffer, { onProgress: (event) => { process.stdout.write(`\rProgress: ${event.overallProgress.toFixed(1)}%`); }, }); console.log('\nUpload complete:', result); } ``` -------------------------------- ### Upload File with Parallel Parts and Progress (TypeScript) Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Shows how to upload a file using the `uploadFile` method with advanced options. This includes setting a webhook URL, custom concurrency, detailed progress and part completion callbacks, and using an AbortSignal for cancellation. It emphasizes parallel upload features like concurrent requests and streaming reads. ```typescript const result = await uploader.uploadFile(file, { webhookUrl: 'https://your-server.com/webhook', concurrency: 5, // Upload 5 parts simultaneously (default: 3) onProgress: (event) => { console.log(`Part ${event.currentPart}/${event.totalParts}`); console.log(`Overall: ${event.overallProgress}%`); }, onPartComplete: (result) => { console.log(`Part ${result.partNumber} ${result.success ? 'done' : 'failed'}`); }, signal: abortController.signal, // For cancellation }); // Parallel Upload Features: // - Concurrent requests: Multiple parts upload simultaneously (configurable) // - Streaming reads: Chunks read on-demand, not loaded into memory // - Independent retries: Failed parts retry without blocking others // - Progress tracking: Real-time progress for each part and overall ``` -------------------------------- ### ChunkedUploader Client Initialization Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Initializes a new ChunkedUploader client instance with server details, API key, and optional configuration for timeouts, concurrency, retries, and retry delay. ```APIDOC ## Initialize ChunkedUploader Client ### Description Create a new uploader instance with server URL and API key for management operations. ### Method `new ChunkedUploader()` ### Parameters #### Constructor Options - **baseUrl** (string) - Required - The base URL of the chunked upload server. - **apiKey** (string) - Required - The API key for authentication. - **timeout** (number) - Optional - Request timeout in milliseconds (default: 30000). - **concurrency** (number) - Optional - Number of parallel uploads (default: 3). - **retryAttempts** (number) - Optional - Number of retry attempts for failed chunks (default: 3). - **retryDelay** (number) - Optional - Delay between retries in milliseconds (default: 1000). ### Request Example ```typescript import { ChunkedUploader } from 'chunked-uploader-sdk'; const uploader = new ChunkedUploader({ baseUrl: 'https://upload.example.com', apiKey: 'your-api-key', timeout: 30000, concurrency: 5, retryAttempts: 3, retryDelay: 1000, }); ``` ### Response No direct response, returns an initialized `ChunkedUploader` instance. ``` -------------------------------- ### Initialize ChunkedUploader Client Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Creates a new instance of the ChunkedUploader client, configuring essential parameters like server URL, API key, and upload settings. Dependencies include the 'chunked-uploader-sdk' library. It takes server connection details and optional parameters for request timeout, concurrency, and retry logic. ```typescript import { ChunkedUploader } from 'chunked-uploader-sdk'; const uploader = new ChunkedUploader({ baseUrl: 'https://upload.example.com', apiKey: 'your-api-key', timeout: 30000, // Request timeout in ms (default: 30000) concurrency: 5, // Parallel uploads (default: 3) retryAttempts: 3, // Retry failed chunks (default: 3) retryDelay: 1000, // Delay between retries in ms (default: 1000) }); ``` -------------------------------- ### Resume Interrupted Upload (TypeScript) Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Illustrates how to resume a previously interrupted upload using the `resumeUpload` method. It requires the `uploadId` and a map of `partTokens` obtained during the initial upload phase. Progress tracking is also supported. ```typescript // Store part tokens from initial upload const tokenMap = new Map(); initResponse.parts.forEach(p => tokenMap.set(p.part, p.token)); // Later, resume the upload const result = await uploader.resumeUpload(uploadId, file, { partTokens: tokenMap, onProgress: (event) => console.log(`${event.overallProgress}%`), }); ``` -------------------------------- ### Initialize Upload Session Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Manually initializes an upload session on the server, retrieving essential metadata like upload ID, total parts, chunk size, expiration time, and part tokens. ```APIDOC ## Initialize Upload Session ### Description Manually initialize an upload session to get part tokens and upload metadata before uploading chunks. ### Method `uploader.initUpload(fileName: string, fileSize: number, webhookUrl?: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **fileName** (string) - Required - The name of the file to be uploaded. - **fileSize** (number) - Required - The total size of the file in bytes. - **webhookUrl** (string) - Optional - A URL to receive status updates for this upload session. ### Request Example ```typescript const file = document.querySelector('input[type="file"]').files[0]; const initResponse = await uploader.initUpload( file.name, file.size, 'https://your-server.com/webhook' // Optional webhook URL ); console.log(`Upload ID: ${initResponse.file_id}`); console.log(`Total parts: ${initResponse.total_parts}`); console.log(`Chunk size: ${initResponse.chunk_size} bytes`); console.log(`Expires at: ${initResponse.expires_at}`); // Access part tokens for manual upload initResponse.parts.forEach(part => { console.log(`Part ${part.part}: token ${part.token}`); }); ``` ### Response #### Success Response (200) - **file_id** (string) - The unique identifier for the upload session. - **total_parts** (number) - The total number of parts the file will be split into. - **chunk_size** (number) - The size of each chunk in bytes. - **expires_at** (string) - The timestamp when the upload session expires. - **parts** (array) - An array of objects, each containing information for a part: - **part** (number) - The part number. - **token** (string) - The unique token required to upload this part. #### Response Example ```json { "file_id": "init-upload-session-id", "total_parts": 200, "chunk_size": 52428800, // 50MB "expires_at": "2023-10-27T10:00:00Z", "parts": [ { "part": 1, "token": "part-token-1" }, { "part": 2, "token": "part-token-2" }, // ... more parts ] } ``` ``` -------------------------------- ### Manual Chunk Upload with Full Control Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Allows custom upload logic with complete control over initialization, chunk upload, and completion. This method is useful for advanced scenarios requiring granular management of the upload process. It involves initializing an upload session, uploading each part individually, and then completing the upload. ```typescript async function manualChunkedUpload(file) { // Step 1: Initialize upload session const init = await uploader.initUpload(file.name, file.size); console.log(`Initialized upload: ${init.file_id}`); console.log(`Will upload ${init.total_parts} parts of ${init.chunk_size} bytes`); const chunkSize = init.chunk_size; const uploadedParts = []; // Step 2: Upload each part manually for (let i = 0; i < init.parts.length; i++) { const part = init.parts[i]; const start = part.part * chunkSize; const end = Math.min(start + chunkSize, file.size); const chunk = file.slice(start, end); console.log(`Uploading part ${part.part + 1}/${init.total_parts}...`); try { const result = await uploader.uploadPart( init.file_id, part.part, part.token, chunk ); uploadedParts.push({ part: result.part_number, checksum: result.checksum_sha256, }); console.log(` ✓ Part ${part.part + 1} uploaded (${result.checksum_sha256.slice(0, 8)}...)`); } catch (error) { console.error(` ✗ Part ${part.part + 1} failed: ${error.message}`); throw error; } } // Step 3: Complete the upload console.log('Completing upload...'); const complete = await uploader.completeUpload(init.file_id); console.log('Upload complete!'); console.log(` Final path: ${complete.final_path}`); console.log(` Storage: ${complete.storage_backend}`); return complete; } ``` -------------------------------- ### Upload Completion API Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Completes the upload process on the server. Requires API Key authentication. ```APIDOC ## POST /upload/{id}/complete ### Description Signals the server that all chunks have been uploaded and the upload process should be finalized. Requires API Key authentication. ### Method POST ### Endpoint /upload/{id}/complete ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the upload. #### Query Parameters - **apiKey** (string) - Required - The API key for authentication. ### Request Body This endpoint typically does not require a request body, as the completion is triggered by the upload ID. ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the upload has been completed successfully. #### Response Example ```json { "message": "Upload completed successfully." } ``` ``` -------------------------------- ### Cancellable Upload using AbortController Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Demonstrates how to cancel an ongoing upload request using the `AbortController` API. It includes setting up an event listener for a cancel button and handling the 'Upload aborted' error. This requires a `file` and the `uploader` instance. ```typescript const abortController = new AbortController(); // Cancel button cancelButton.addEventListener('click', () => { abortController.abort(); }); const result = await uploader.uploadFile(file, { signal: abortController.signal, onProgress: (event) => { console.log(`${event.overallProgress}%`); }, }); if (!result.success && result.error?.message === 'Upload aborted') { console.log('Upload was cancelled'); } ``` -------------------------------- ### Node.js File Upload from Disk Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Uploads files from disk in a Node.js environment using either a Buffer or file streams. It utilizes the ChunkedUploader class and provides progress feedback. Dependencies include 'chunked-uploader-sdk', 'fs/promises', and 'fs'. ```typescript import { ChunkedUploader } from 'chunked-uploader-sdk'; import { readFile } from 'fs/promises'; import { createReadStream } from 'fs'; const uploader = new ChunkedUploader({ baseUrl: 'http://localhost:3000', apiKey: 'server-api-key', concurrency: 8, // Higher concurrency for server-side }); async function uploadFile(filePath) { // Read entire file into buffer const buffer = await readFile(filePath); const result = await uploader.uploadFile(buffer, { onProgress: (event) => { const percent = event.overallProgress.toFixed(1); const mbUploaded = ((event.uploadedParts * 50)).toFixed(0); process.stdout.write(`\rUploading: ${percent}% (${mbUploaded}MB)`); }, }); console.log('\n'); if (result.success) { console.log(`✓ Upload complete: ${result.finalPath}`); console.log(` File ID: ${result.fileId}`); console.log(` Size: ${(result.totalSize / 1024 / 1024).toFixed(2)}MB`); } else { console.error(`✗ Upload failed: ${result.error.message}`); } return result; } // Upload a large video file uploadFile('/path/to/large-video.mp4'); ``` -------------------------------- ### Complete Upload Assembly Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Finalizes the upload process by assembling all successfully uploaded parts into a single file on the server. ```APIDOC ## Complete Upload Assembly ### Description Finalize the upload by assembling all uploaded parts into a single file on the server. ### Method POST ### Endpoint `/upload/complete/{upload_id}` (assumed, based on context) ### Parameters #### Path Parameters - **upload_id** (string) - Required - The unique identifier for the upload session. #### Query Parameters None #### Request Body None ### Request Example (TypeScript code example provided in source illustrates usage, not a direct JSON request body) ### Response #### Success Response (200) - **status** (string) - The status of the completion request (e.g., 'completed'). - **file_id** (string) - The unique identifier of the assembled file. - **filename** (string) - The name of the final assembled file. - **total_size** (integer) - The total size of the assembled file in bytes. - **final_path** (string) - The server path where the assembled file is stored. - **storage_backend** (string) - The storage backend used for the file (e.g., 'S3', 'GCS'). #### Response Example ```json { "status": "completed", "file_id": "unique-file-identifier", "filename": "my_document.pdf", "total_size": 104857600, "final_path": "/path/to/storage/my_document.pdf", "storage_backend": "S3" } ``` ``` -------------------------------- ### Upload Progress API Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Retrieves the current progress of an ongoing upload. Requires API Key authentication. ```APIDOC ## GET /upload/{id}/status ### Description Retrieves the current progress and status of an ongoing file upload. Requires API Key authentication. ### Method GET ### Endpoint /upload/{id}/status ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the upload. #### Query Parameters - **apiKey** (string) - Required - The API key for authentication. ### Request Body None ### Response #### Success Response (200) - **progress** (integer) - The upload progress in percentage (0-100). - **status** (string) - The current status of the upload (e.g., 'uploading', 'completed', 'failed'). #### Response Example ```json { "progress": 50, "status": "uploading" } ``` ``` -------------------------------- ### Check Server Health Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Verifies the availability and operational status of the upload server. ```APIDOC ## Check Server Health ### Description Verify the upload server is available and operational before starting uploads. ### Method GET ### Endpoint `/health` (assumed, based on context) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example (TypeScript code example provided in source illustrates usage, not a direct JSON request body) ### Response #### Success Response (200) - **status** (string) - The health status of the server (e.g., 'ok', 'degraded', 'error'). #### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### Cancellable Upload with AbortController in TypeScript Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Implements user-cancellable uploads by integrating with the AbortController API. It allows a user to abort an in-progress upload via a button click and handles the cancellation logic, updating the UI with progress and status messages. ```typescript const abortController = new AbortController(); // Setup cancel button document.getElementById('cancelBtn').addEventListener('click', () => { abortController.abort(); console.log('Upload cancelled by user'); }); try { const result = await uploader.uploadFile(file, { signal: abortController.signal, onProgress: (event) => { const progress = event.overallProgress.toFixed(1); document.getElementById('progress').textContent = `${progress}%`; }, }); if (result.success) { console.log('Upload completed:', result.finalPath); } } catch (error) { if (error.message === 'Upload aborted') { console.log('Upload was cancelled'); } else { console.error('Upload failed:', error); } } ``` -------------------------------- ### Upload File with Progress Tracking Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Uploads a file using automatic chunking and provides real-time progress callbacks for overall upload percentage and individual part completion. ```APIDOC ## Upload File with Progress Tracking ### Description Upload a file with automatic chunking and real-time progress callbacks showing upload percentage and part completion. ### Method `uploader.uploadFile(file: File, options?: UploadFileOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `file`: The `File` object to upload. `options` (UploadFileOptions): - **webhookUrl** (string) - Optional - URL to receive upload status notifications. - **concurrency** (number) - Optional - Overrides the default concurrency setting for this upload. - **onProgress** (function) - Optional - Callback function for overall upload progress. - `event.fileId`: ID of the file being uploaded. - `event.currentPart`: The current part number being processed. - `event.totalParts`: The total number of parts for the file. - `event.overallProgress`: The overall upload progress percentage. - `event.uploadedParts`: The number of parts successfully uploaded so far. - **onPartComplete** (function) - Optional - Callback function when a part is uploaded successfully. - `result.success`: Boolean indicating if the part upload was successful. - `result.partNumber`: The number of the part that was uploaded. - `result.response`: The response from the server for the part upload. - `result.error`: Error object if the part upload failed. - **onPartError** (function) - Optional - Callback function when a part upload fails. - `partNumber`: The number of the part that failed. - `error`: The error object from the failed upload. - `attempt`: The current retry attempt number. ### Request Example ```typescript const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; try { const result = await uploader.uploadFile(file, { webhookUrl: 'https://your-server.com/webhook', concurrency: 10, // Override default concurrency onProgress: (event) => { console.log(`Upload ID: ${event.fileId}`); console.log(`Part ${event.currentPart + 1}/${event.totalParts}`); console.log(`Progress: ${event.overallProgress.toFixed(1)}%`); console.log(`Uploaded: ${event.uploadedParts} parts`); }, onPartComplete: (result) => { if (result.success) { console.log(`Part ${result.partNumber} uploaded successfully`); console.log(`Checksum: ${result.response.checksum_sha256}`); } else { console.error(`Part ${result.partNumber} failed:`, result.error); } }, onPartError: (partNumber, error, attempt) => { console.warn(`Part ${partNumber} failed on attempt ${attempt}: ${error.message}`); }, }); if (result.success) { console.log('Upload complete!'); console.log(`File ID: ${result.fileId}`); console.log(`Final path: ${result.finalPath}`); console.log(`Storage backend: ${result.storageBackend}`); } else { console.error('Upload failed:', result.error.message); } } catch (error) { console.error('Upload error:', error); } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the overall upload was successful. - **fileId** (string) - The unique identifier for the uploaded file. - **finalPath** (string) - The final path or URL of the uploaded file. - **storageBackend** (string) - The storage backend used for the upload. #### Error Response - **success** (boolean) - Always `false`. - **error** (object) - An error object containing details about the failure. - **message** (string) - A description of the error. #### Response Example (Success) ```json { "success": true, "fileId": "some-unique-file-id", "finalPath": "/path/to/uploaded/file.mp4", "storageBackend": "s3" } ``` #### Response Example (Failure) ```json { "success": false, "error": { "message": "Upload failed due to network issues." } } ``` ``` -------------------------------- ### Upload a Single Chunk (TypeScript) Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Demonstrates the `uploadPart` method for uploading a specific chunk of data. It requires the `uploadId`, the `partNumber`, the `token` for that part, the `chunkData` itself, and an optional `signal` for cancellation. ```typescript const result = await uploader.uploadPart( uploadId, 0, partToken, chunkData ); ``` -------------------------------- ### Upload File with Progress Tracking Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Uploads a file using the ChunkedUploader, automatically handling chunking and parallel transfers. It provides real-time progress updates via callbacks for overall progress, part completion, and error handling. Input is a File object and optional upload configurations. Output includes success status, file ID, and final path. ```typescript const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; try { const result = await uploader.uploadFile(file, { webhookUrl: 'https://your-server.com/webhook', concurrency: 10, // Override default concurrency onProgress: (event) => { console.log(`Upload ID: ${event.fileId}`); console.log(`Part ${event.currentPart + 1}/${event.totalParts}`); console.log(`Progress: ${event.overallProgress.toFixed(1)}%`); console.log(`Uploaded: ${event.uploadedParts} parts`); }, onPartComplete: (result) => { if (result.success) { console.log(`Part ${result.partNumber} uploaded successfully`); console.log(`Checksum: ${result.response.checksum_sha256}`); } else { console.error(`Part ${result.partNumber} failed:`, result.error); } }, onPartError: (partNumber, error, attempt) => { console.warn(`Part ${partNumber} failed on attempt ${attempt}: ${error.message}`); }, }); if (result.success) { console.log('Upload complete!'); console.log(`File ID: ${result.fileId}`); console.log(`Final path: ${result.finalPath}`); console.log(`Storage backend: ${result.storageBackend}`); } else { console.error('Upload failed:', result.error.message); } } catch (error) { console.error('Upload error:', error); } ``` -------------------------------- ### Error Handling Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Details on how the SDK handles and reports errors using `ChunkedUploaderError`. ```APIDOC ## Error Handling ### Description The SDK throws `ChunkedUploaderError` to indicate API-related errors during upload operations. This allows for specific handling of upload failures. ### Code Example ```typescript import { ChunkedUploaderError } from 'chunked-uploader-sdk'; try { await uploader.uploadFile(file); } catch (error) { if (error instanceof ChunkedUploaderError) { console.error('Upload error:', error.message); console.error('Status code:', error.statusCode); console.error('Error code:', error.code); } else { console.error('An unexpected error occurred:', error); } } ``` ### Error Properties - **message** (string) - A human-readable description of the error. - **statusCode** (number) - The HTTP status code returned by the server. - **code** (string) - An application-specific error code for more granular error handling. ``` -------------------------------- ### Upload File with Progress and Part Status UI Updates Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Shows how to integrate upload progress and individual part completion status into a user interface. It updates a progress bar and status text elements based on the upload events. This snippet relies on the `uploader` instance and a `file` variable being available from a previous context. ```typescript const progressBar = document.querySelector('.progress-bar') as HTMLElement; const statusText = document.querySelector('.status') as HTMLElement; const result = await uploader.uploadFile(file, { onProgress: (event) => { progressBar.style.width = `${event.overallProgress}%`; statusText.textContent = `Uploading part ${event.uploadedParts}/${event.totalParts}`; }, onPartComplete: (result) => { if (!result.success) { console.error(`Part ${result.partNumber} failed:`, result.error); } }, }); ``` -------------------------------- ### Error Handling with Custom Error Class Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Demonstrates how to handle SDK errors using the `ChunkedUploaderError` class, which provides status codes and specific error details. This allows for targeted error management based on common HTTP status codes and SDK-defined error codes. ```typescript import { ChunkedUploader, ChunkedUploaderError } from 'chunked-uploader-sdk'; try { const result = await uploader.uploadFile(file); console.log('Success:', result); } catch (error) { if (error instanceof ChunkedUploaderError) { console.error('Upload error:', error.message); console.error('Status code:', error.statusCode); console.error('Error code:', error.code); if (error.statusCode === 401) { console.error('Authentication failed - check your API key'); } else if (error.statusCode === 413) { console.error('File too large for server limits'); } else if (error.statusCode === 404) { console.error('Upload session not found - may have expired'); } else if (error.code === 'UPLOAD_EXPIRED') { console.error('Upload session expired - start a new upload'); } else { console.error('Details:', error.details); } } else { console.error('Unexpected error:', error); } } ``` -------------------------------- ### Resumable Upload with Local Storage Token Management Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Implements resumable uploads by storing upload tokens in `localStorage`. It checks for existing uploads, attempts to resume, and if unsuccessful or no prior upload exists, initiates a new upload and stores its tokens. This requires a `File` object and the `uploader` instance. ```typescript const STORAGE_KEY = 'pending_upload'; interface StoredUpload { uploadId: string; tokens: [number, string][]; } async function uploadWithResume(file: File) { // Check for existing upload const stored = localStorage.getItem(STORAGE_KEY); if (stored) { const data: StoredUpload = JSON.parse(stored); const tokenMap = new Map(data.tokens); try { const result = await uploader.resumeUpload(data.uploadId, file, { partTokens: tokenMap, }); if (result.success) { localStorage.removeItem(STORAGE_KEY); return result; } } catch (error) { console.log('Resume failed, starting fresh'); } } // Start new upload const initResponse = await uploader.initUpload(file.name, file.size); // Store tokens for resume const toStore: StoredUpload = { uploadId: initResponse.file_id, tokens: initResponse.parts.map(p => [p.part, p.token]), }; localStorage.setItem(STORAGE_KEY, JSON.stringify(toStore)); // Upload file const tokenMap = new Map(initResponse.parts.map(p => [p.part, p.token])); // Manual upload with stored tokens const result = await uploader.resumeUpload(initResponse.file_id, file, { partTokens: tokenMap, }); if (result.success) { localStorage.removeItem(STORAGE_KEY); } return result; } ``` -------------------------------- ### Resumable Upload with localStorage Persistence (TypeScript) Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt This function enables resumable file uploads by leveraging localStorage to store and retrieve upload state. It checks for existing upload data, attempts to resume if the file matches, or initiates a new upload and saves its state. Dependencies include the `uploader` object with `initUpload` and `resumeUpload` methods. It takes a `File` object as input and returns the upload result. Error handling is included for parsing stored data and for failed resume attempts. ```typescript const STORAGE_KEY = 'chunked_upload_state'; interface StoredUploadState { uploadId: string; filename: string; fileSize: number; tokens: [number, string][]; timestamp: number; } async function uploadWithAutoResume(file) { // Check for existing upload state const stored = localStorage.getItem(STORAGE_KEY); if (stored) { try { const state = JSON.parse(stored); // Check if stored state matches current file if (state.filename === file.name && state.fileSize === file.size) { console.log(`Found existing upload: ${state.uploadId}`); console.log('Attempting to resume...'); const tokenMap = new Map(state.tokens); const result = await uploader.resumeUpload(state.uploadId, file, { partTokens: tokenMap, onProgress: (event) => { console.log(`Resume progress: ${event.overallProgress.toFixed(1)}%`); }, }); if (result.success) { localStorage.removeItem(STORAGE_KEY); console.log('Resume successful!'); return result; } } } catch (error) { console.log('Resume failed, starting new upload:', error.message); localStorage.removeItem(STORAGE_KEY); } } // Start new upload console.log('Starting new upload...'); const initResponse = await uploader.initUpload(file.name, file.size); // Store state for resume const state = { uploadId: initResponse.file_id, filename: file.name, fileSize: file.size, tokens: initResponse.parts.map(p => [p.part, p.token]), timestamp: Date.now(), }; localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); // Upload with stored tokens const tokenMap = new Map(state.tokens); const result = await uploader.resumeUpload(initResponse.file_id, file, { partTokens: tokenMap, onProgress: (event) => { console.log(`Upload progress: ${event.overallProgress.toFixed(1)}%`); }, }); if (result.success) { localStorage.removeItem(STORAGE_KEY); console.log('Upload completed!'); } return result; } ``` -------------------------------- ### Complete Upload Assembly with TypeScript Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Finalizes the upload process by assembling all previously uploaded parts into a single file on the server. Requires the upload ID. Logs the final status, file details, and storage information. ```typescript try { const result = await uploader.completeUpload('upload-id-here'); console.log(`Upload completed: ${result.status}`); console.log(`File ID: ${result.file_id}`); console.log(`Filename: ${result.filename}`); console.log(`Total size: ${result.total_size} bytes`); console.log(`Final path: ${result.final_path}`); console.log(`Storage: ${result.storage_backend}`); } catch (error) { console.error('Complete failed:', error.message); } ``` -------------------------------- ### Resume Interrupted Upload Source: https://context7.com/dickwu/chunked-uploader-sdk-ts/llms.txt Resumes a previously interrupted upload by using a stored upload ID and part tokens. This allows the upload to continue from where it left off. ```APIDOC ## Resume Interrupted Upload ### Description Resume a previously interrupted upload by providing the upload ID and stored part tokens from the initial upload. ### Method `uploader.resumeUpload(uploadId: string, file: File, options: ResumeUploadOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `uploadId`: The unique identifier of the upload session to resume. `file`: The `File` object being uploaded. `options` (ResumeUploadOptions): - **partTokens** (Map) - A Map where keys are part numbers and values are the corresponding upload tokens. - **onProgress** (function) - Callback function for overall upload progress during resume. - `event.overallProgress`: The overall upload progress percentage. ### Request Example ```typescript // During initial upload, store tokens for resume capability const initResponse = await uploader.initUpload('video.mp4', file.size); const tokenMap = new Map(); initResponse.parts.forEach(p => tokenMap.set(p.part, p.token)); // Store tokens in localStorage or database localStorage.setItem('upload_tokens', JSON.stringify({ uploadId: initResponse.file_id, tokens: Array.from(tokenMap.entries()), })); // Later, resume the upload after interruption const stored = JSON.parse(localStorage.getItem('upload_tokens')); const restoredTokens = new Map(stored.tokens); const result = await uploader.resumeUpload(stored.uploadId, file, { partTokens: restoredTokens, onProgress: (event) => { console.log(`Resuming: ${event.overallProgress.toFixed(1)}%`); }, }); if (result.success) { localStorage.removeItem('upload_tokens'); console.log('Upload completed:', result.finalPath); } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the overall upload was successful. - **fileId** (string) - The unique identifier for the uploaded file. - **finalPath** (string) - The final path or URL of the uploaded file. - **storageBackend** (string) - The storage backend used for the upload. #### Response Example ```json { "success": true, "fileId": "resumed-upload-id", "finalPath": "/path/to/resumed/file.mp4", "storageBackend": "s3" } ``` ``` -------------------------------- ### Health Check API Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Performs a health check on the server. ```APIDOC ## GET /health ### Description Checks the health status of the Chunked Upload Server. ### Method GET ### Endpoint /health ### Parameters None ### Request Body None ### Response #### Success Response (200) - **status** (string) - Indicates the health status of the server (e.g., 'OK'). #### Response Example ```json { "status": "OK" } ``` ``` -------------------------------- ### Chunk Upload API Source: https://github.com/dickwu/chunked-uploader-sdk-ts/blob/main/README.md Uploads a specific chunk of the file. Requires JWT authentication per part. ```APIDOC ## PUT /upload/{id}/part/{n} ### Description Uploads a specific chunk of the file to the server. Authentication is required for each part uploaded using a JWT token. ### Method PUT ### Endpoint /upload/{id}/part/{n} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the upload. - **n** (integer) - Required - The sequence number of the chunk being uploaded. #### Query Parameters - **jwt** (string) - Required - The JSON Web Token for authenticating this specific chunk upload. ### Request Body - **chunkData** (binary) - Required - The binary data of the file chunk. ### Request Example (Request body is binary data, not typically represented in JSON) ### Response #### Success Response (200) - **success** (boolean) - Indicates if the chunk upload was successful. #### Response Example ```json { "success": true } ``` ```