### Example App Setup and Start Source: https://github.com/cap-go/capacitor-uploader/blob/main/AGENTS.md Sets up and starts the example application locally. This involves navigating to the example app directory, installing its dependencies, and starting the development server. ```bash cd example-app bun install bun run start ``` -------------------------------- ### Install and Start Example App Source: https://github.com/cap-go/capacitor-uploader/blob/main/example-app/README.md Installs project dependencies and starts the development server for the example application. ```bash npm install npm start ``` -------------------------------- ### Install Capacitor Uploader Plugin Source: https://github.com/cap-go/capacitor-uploader/blob/main/README.md Install the plugin using npm and sync with Capacitor. This is the initial setup step for using the uploader. ```bash npm install @capgo/capacitor-uploader npx cap sync ``` -------------------------------- ### Minimal Complete Upload Example Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Demonstrates how to start an upload and listen for its events (uploading, completed, failed). Ensure to implement `getToken()` and handle errors appropriately. ```typescript import { Uploader, UploadEvent } from '@capgo/capacitor-uploader'; export async function uploadFile(filePath: string) { try { // Start upload const { id } = await Uploader.startUpload({ filePath, serverUrl: 'https://api.example.com/upload', headers: { 'Authorization': 'Bearer ' + getToken() } }); console.log('Upload started:', id); // Listen for events const listener = await Uploader.addListener('events', (event: UploadEvent) => { if (event.name === 'uploading') { console.log('Progress:', event.payload.percent, '%'); } else if (event.name === 'completed') { console.log('Success!'); } else if (event.name === 'failed') { console.error('Failed:', event.payload.error); } }); return id; } catch (error) { console.error('Upload failed:', error); throw error; } } ``` -------------------------------- ### Simple Upload Pattern Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Basic example of starting an upload with a file path, server URL, and empty headers. ```typescript const { id } = await Uploader.startUpload({ filePath: 'file:///path/to/file.jpg', serverUrl: 'https://api.example.com/upload', headers: {} }); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/cap-go/capacitor-uploader/blob/main/CONTRIBUTING.md Run this command to install all necessary Node.js dependencies for the project. ```shell npm install ``` -------------------------------- ### Upload with Authentication Pattern Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Example of starting an upload with an Authorization header for authentication. ```typescript const { id } = await Uploader.startUpload({ filePath: 'file:///path/to/file.jpg', serverUrl: 'https://api.example.com/upload', headers: { 'Authorization': 'Bearer ' + token } }); ``` -------------------------------- ### Uploader Web Usage Example Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-web.md Demonstrates how to initialize the Uploader, listen for upload events (uploading, completed, failed), start a new upload with various options, and cancel an ongoing upload. ```typescript import { Uploader } from '@capgo/capacitor-uploader'; // Listen for events Uploader.addListener('events', (event) => { switch (event.name) { case 'uploading': console.log(`Progress: ${event.payload.percent}%`); break; case 'completed': console.log(`Success: HTTP ${event.payload.statusCode}`); break; case 'failed': console.error(`Error: ${event.payload.error}`); break; } }); // Start an upload const { id } = await Uploader.startUpload({ filePath: 'file:///Documents/photo.jpg', serverUrl: 'https://api.example.com/upload', method: 'POST', uploadType: 'multipart', parameters: { userId: '123' }, maxRetries: 3 }); // Cancel if needed await Uploader.removeUpload({ id }); ``` -------------------------------- ### Install Dependencies and Build Plugin Source: https://github.com/cap-go/capacitor-uploader/blob/main/AGENTS.md Installs project dependencies and builds the plugin using Bun. This is a foundational step for development and verification. ```bash bun install bun run build ``` -------------------------------- ### Upload from IndexedDB Pattern (Web Only) Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Example of starting an upload from a file path stored in IndexedDB, specific to the web platform. ```typescript const { id } = await Uploader.startUpload({ filePath: 'idb://myapp/documents/doc-uuid-123', serverUrl: 'https://api.example.com/upload', headers: {} }); ``` -------------------------------- ### IndexedDB Path Examples Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/path-helper.md Examples of valid and invalid IndexedDB paths, demonstrating the expected format for database, store, and key components. ```plaintext idb://myapp/blobs/upload-123 idb://database-name/object-store/key-with-hyphens idb://db1/files/2024-01-15_photo.jpg idb://cache/thumbnails/large/product-456 ``` ```plaintext idb:// (missing all parts) idb://db (missing store and key) idb://db/store (missing key) idb://db/store/ (empty key) idb:///store/key (empty database) idb://db//key (empty store) file:///local/path (wrong scheme) ``` -------------------------------- ### startUpload Method Signature Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Signature for starting an upload. Requires serverUrl, headers, and either filePath or files. Returns an upload ID. ```typescript startUpload(options: uploadOption): Promise<{ id: string }> ``` -------------------------------- ### Minimal uploadOption Configuration Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Provides a basic setup for initiating a file upload using `filePath` and `serverUrl`. ```typescript const uploadOption: uploadOption = { filePath: 'file:///path/to/file.jpg', serverUrl: 'https://api.example.com/upload', headers: {} }; ``` -------------------------------- ### Basic Listener Cleanup Example Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Shows how to add a listener and subsequently remove it using the returned PluginListenerHandle. ```typescript const listener = await Uploader.addListener('events', (event) => { console.log('Upload event:', event.name); }); // Later, remove the listener await listener.remove(); ``` -------------------------------- ### Binary Upload Example Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-web.md Initiates a binary upload, suitable for PUT requests or APIs expecting raw data. Only a single file can be uploaded this way. ```typescript const result = await Uploader.startUpload({ url: 'https://example.com/upload/resource', filePath: 'idb://my-db/my-files/data.bin', name: 'data.bin', uploadType: 'binary', // method: 'PUT' // Explicitly set or default for binary }); console.log('Binary upload started with ID:', result.id); ``` -------------------------------- ### Uploading Event Example Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Example of an UploadEvent object representing an ongoing upload with progress percentage. ```typescript const event: UploadEvent = { name: 'uploading', id: 'abc123xyz', payload: { percent: 75 } }; ``` -------------------------------- ### Install SwiftLint on macOS Source: https://github.com/cap-go/capacitor-uploader/blob/main/CONTRIBUTING.md Install SwiftLint using Homebrew, a dependency manager for macOS. This is required for Swift code quality checks. ```shell brew install swiftlint ``` -------------------------------- ### Multiple Files Upload Pattern Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Example of uploading multiple files with specified field names for each. ```typescript const { id } = await Uploader.startUpload({ serverUrl: 'https://api.example.com/photos', method: 'POST', uploadType: 'multipart', headers: {}, files: [ { filePath: 'file:///photo1.jpg', fieldName: 'images[]' }, { filePath: 'file:///photo2.jpg', fieldName: 'images[]' } ] }); ``` -------------------------------- ### Simple File Upload Configuration Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Example of configuring a single file with only the required filePath. The fieldName and mimeType will use their default values. ```typescript const file1: UploadFileOption = { filePath: 'file:///images/photo1.jpg' }; ``` -------------------------------- ### Handling Binary Upload with Multiple Files Error Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/errors.md Provides an example of catching the 'Binary uploads only support a single file' error and guiding the user to use the correct upload method. ```typescript try { await Uploader.startUpload({ files: multipleFiles, method: 'PUT', serverUrl: presignedUrl, headers: {} }); } catch (error) { if ((error as Error).message.includes('Binary uploads only support')) { console.error('Use POST with multipart for multiple files, or PUT with a single file'); } } ``` -------------------------------- ### Upload to Custom Server with POST Source: https://github.com/cap-go/capacitor-uploader/blob/main/README.md Starts a file upload to a custom server using the POST method. Includes options for authentication headers, custom parameters, and retry attempts. It also sets up event listeners for upload status. ```typescript import { Uploader } from '@capgo/capacitor-uploader'; async function uploadToCustomServer(filePath: string, serverUrl: string) { try { // Start the upload const { id } = await Uploader.startUpload({ filePath: filePath, serverUrl: serverUrl, method: 'POST', headers: { 'Authorization': 'Bearer your-auth-token-here' }, parameters: { 'user_id': '12345', 'file_type': 'image' }, notificationTitle: 'Uploading to Custom Server', maxRetries: 3 }); console.log('Upload started with ID:', id); // Listen for upload events Uploader.addListener('events', (event) => { switch (event.name) { case 'uploading': console.log(`Upload progress: ${event.payload.percent}%`); break; case 'completed': console.log('Upload completed successfully'); console.log('Server response status code:', event.payload.statusCode); break; case 'failed': console.error('Upload failed:', event.payload.error); break; } }); // Optional: Remove the upload if needed // await Uploader.removeUpload({ id: id }); } catch (error) { console.error('Failed to start upload:', error); } } // Usage const filePath = 'file:///path/to/your/file.jpg'; const serverUrl = 'https://your-custom-server.com/upload'; uploadToCustomServer(filePath, serverUrl); ``` -------------------------------- ### Completed Event Example Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Example of an UploadEvent object indicating a successful upload with an HTTP status code. ```typescript const event: UploadEvent = { name: 'completed', id: 'abc123xyz', payload: { statusCode: 200 } }; ``` -------------------------------- ### Start Binary Upload to S3 Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-plugin.md Perform a binary upload to a presigned S3 URL. Requires the file path, S3 URL, HTTP method, and MIME type. Optional notification title can be provided. ```typescript const { id } = await Uploader.startUpload({ filePath: 'file:///path/to/file.jpg', serverUrl: 'https://bucket.s3.amazonaws.com/key?X-Amz-Algorithm=...', method: 'PUT', uploadType: 'binary', mimeType: 'image/jpeg', notificationTitle: 'Uploading to S3' }); console.log('Upload started:', id); ``` -------------------------------- ### Start Upload from IndexedDB Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-plugin.md Initiate an upload using a file path stored in IndexedDB. The plugin supports 'idb://' URIs for accessing files stored locally. ```typescript const { id } = await Uploader.startUpload({ filePath: 'idb://myDatabase/files/document123', serverUrl: 'https://api.example.com/upload', method: 'POST' }); ``` -------------------------------- ### Multi-File Upload Configuration Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Example demonstrating how to configure multiple files for a single upload request using the 'files' array within uploadOption. Each file can have its own filePath, fieldName, and mimeType. ```typescript const uploadOption: uploadOption = { serverUrl: 'https://api.example.com/bulk-upload', method: 'POST', uploadType: 'multipart', headers: { 'Authorization': 'Bearer token' }, files: [ { filePath: 'file:///images/cover.jpg', fieldName: 'cover', mimeType: 'image/jpeg' }, { filePath: 'file:///images/thumbnail.jpg', fieldName: 'thumbnail', mimeType: 'image/jpeg' }, { filePath: 'file:///documents/manifest.json', fieldName: 'metadata', mimeType: 'application/json' } ] }; ``` -------------------------------- ### Start Multipart File Upload Source: https://github.com/cap-go/capacitor-uploader/blob/main/README.md Initiates a multipart upload for multiple files. Specify server URL, method, files with their field names and MIME types, and optional parameters and headers. ```typescript import { Uploader } from '@capgo/capacitor-uploader'; const { id } = await Uploader.startUpload({ serverUrl: 'https://api.example.com/upload', method: 'POST', uploadType: 'multipart', files: [ { filePath: 'file:///...photo1.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' }, { filePath: 'file:///...photo2.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' }, ], parameters: { albumId: '7' }, headers: { Authorization: 'Bearer token' }, }); console.log('Upload started with ID:', id); ``` -------------------------------- ### Start Single File Multipart Upload Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-plugin.md Initiate a single file upload to a custom server using multipart form data. Specify file path, server URL, method, file field name, headers, and parameters. Configurable with max retries. ```typescript const { id } = await Uploader.startUpload({ filePath: 'file:///path/to/file.jpg', serverUrl: 'https://api.example.com/upload', method: 'POST', uploadType: 'multipart', fileField: 'photo', headers: { 'Authorization': 'Bearer token123' }, parameters: { 'user_id': '12345', 'file_type': 'image' }, maxRetries: 3 }); console.log('Upload started with ID:', id); ``` -------------------------------- ### Track Upload Progress Pattern Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Example of listening to upload events to update a progress bar, show success, or handle failures. Remember to remove the listener when done. ```typescript const listener = await Uploader.addListener('events', (event) => { switch (event.name) { case 'uploading': updateProgressBar(event.payload.percent || 0); break; case 'completed': showSuccess(`Uploaded with status ${event.payload.statusCode}`); break; case 'failed': showError(event.payload.error); break; } }); // Clean up when done await listener.remove(); ``` -------------------------------- ### Upload to S3 Presigned URL Pattern Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Example of uploading to an S3 presigned URL using the PUT method and binary upload type. ```typescript const { id } = await Uploader.startUpload({ filePath: 'file:///path/to/file.jpg', serverUrl: presignedUrl, method: 'PUT', uploadType: 'binary', headers: {} }); ``` -------------------------------- ### Start an Upload Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-web.md Initiates a file upload and returns an upload ID immediately. The upload proceeds asynchronously in the background. Default maxRetries is 3. ```typescript const result = await Uploader.startUpload({ url: 'https://example.com/upload', filePath: 'idb://my-db/my-files/file1.txt', name: 'file1.txt', // Optional: specify upload type, e.g., 'binary' or 'multipart' // uploadType: 'binary', // Optional: specify max retries // maxRetries: 5, }); console.log('Upload started with ID:', result.id); ``` -------------------------------- ### Start Multiple Files Multipart Upload Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-plugin.md Upload multiple files as multipart form data. Define the server URL, method, and an array of file objects, each with filePath, fieldName, and optional mimeType. Parameters and headers can also be included. ```typescript const { id } = await Uploader.startUpload({ serverUrl: 'https://api.example.com/upload', method: 'POST', uploadType: 'multipart', files: [ { filePath: 'file:///...photo1.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' }, { filePath: 'file:///...photo2.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' }, ], parameters: { 'albumId': '7' }, headers: { 'Authorization': 'Bearer token' } }); ``` -------------------------------- ### Selective Listener Cleanup Example Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Demonstrates adding multiple listeners and removing only specific ones to manage event subscriptions. ```typescript const progressListener = await Uploader.addListener('events', (event) => { if (event.name === 'uploading') { updateProgressUI(event.payload.percent); } }); const completionListener = await Uploader.addListener('events', (event) => { if (event.name === 'completed' || event.name === 'failed') { handleCompletion(event); } }); // Remove only progress listener await progressListener.remove(); // Completion listener is still active ``` -------------------------------- ### getPluginVersion Method Signature Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Signature for getting the plugin version. Returns a version string, or 'web' on the web platform. ```typescript getPluginVersion(): Promise<{ version: string }> ``` -------------------------------- ### Multipart Upload with Form Fields Pattern Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Example of a multipart upload including custom form fields like userId and category. ```typescript const { id } = await Uploader.startUpload({ filePath: 'file:///path/to/file.jpg', serverUrl: 'https://api.example.com/upload', method: 'POST', uploadType: 'multipart', fileField: 'attachment', headers: {}, parameters: { userId: '123', category: 'documents' } }); ``` -------------------------------- ### UploaderPlugin API Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/README.md Documentation for the core UploaderPlugin interface, including methods to initiate uploads, cancel them, add listeners, and get the plugin version. ```APIDOC ## UploaderPlugin Interface This section details the primary interface for interacting with the Capacitor Uploader Plugin. ### `startUpload()` Initiates file uploads. Provides full parameter documentation and examples. ### `removeUpload()` Cancels ongoing file uploads. ### `addListener()` Registers event listeners to receive upload status updates and events. ### `getPluginVersion()` Retrieves the current version of the Uploader plugin. ``` -------------------------------- ### File Upload with Custom Field Name and MIME Type Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Example of configuring a file with a custom field name and explicitly setting the MIME type. Useful for specific server requirements. ```typescript const file2: UploadFileOption = { filePath: 'file:///images/photo2.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' }; ``` -------------------------------- ### Sequentially Upload Multiple Files Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-plugin.md Upload files one after another, waiting for each upload to complete before starting the next. This is useful when order or dependency is important between uploads. ```typescript async function uploadFilesSequentially(files: string[]) { for (const filePath of files) { const { id } = await Uploader.startUpload({ filePath, serverUrl: 'https://api.example.com/upload', headers: { 'Authorization': `Bearer ${token}` } }); // Wait for this upload to complete before starting next await waitForUploadCompletion(id); } } ``` -------------------------------- ### Get Plugin Version Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/overview.md Retrieves the current version of the Capacitor Uploader plugin installed in the project. ```APIDOC ## getPluginVersion() ### Description Retrieves the currently installed version of the Capacitor Uploader plugin. ### Method getPluginVersion ### Returns - **`string`** - The version number of the plugin (e.g., '8.2.1'). ### Example Usage ```typescript const version = await Uploader.getPluginVersion(); console.log('Capacitor Uploader Version:', version); ``` ``` -------------------------------- ### startUpload() Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Initiates a file upload. This method handles the core upload process, supporting various configurations and options. ```APIDOC ## startUpload() ### Description Initiates a file upload. This method handles the core upload process, supporting various configurations and options. ### Method POST ### Endpoint /startUpload ### Parameters #### Request Body - **options** (UploadOption) - Required - Configuration options for the upload. ### Request Example ```json { "options": { "url": "https://example.com/upload", "filePath": "idb://my-db/my-file.txt", "fileName": "file.txt", "fileKey": "file", "headers": { "Authorization": "Bearer YOUR_TOKEN" }, "method": "POST", "data": { "custom": "data" }, "chunkSize": 1024, "retries": 3, "parallelUploads": 2, "onProgress": "listenerId", "onSuccess": "listenerId", "onFailure": "listenerId" } } ``` ### Response #### Success Response (200) - **result** (string) - The upload ID. #### Response Example ```json { "result": "upload-12345" } ``` ``` -------------------------------- ### TypeScript Plugin Interface Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/overview.md Defines the interface for the Uploader plugin, including methods for starting and removing uploads, adding listeners, and getting the plugin version. ```typescript // Plugin interface interface UploaderPlugin { startUpload(options: uploadOption): Promise<{ id: string }>; removeUpload(options: { id: string }): Promise; addListener(eventName: 'events', listenerFunc: (state: UploadEvent) => void): Promise; getPluginVersion(): Promise<{ version: string }>; } ``` -------------------------------- ### startUpload Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-web.md Initiates a new upload operation and returns immediately with an upload ID. The upload proceeds in the background. ```APIDOC ## startUpload ### Description Initiates a new upload operation and returns immediately with an upload ID. The upload proceeds in the background without blocking the caller. ### Method POST ### Endpoint /startUpload ### Parameters #### Request Body - **options** (object) - Required - Upload options. - **url** (string) - Required - The URL to upload to. - **filePath** (string) - Optional - Path to the file to upload (for single file binary uploads). - **files** (array) - Optional - Array of files to upload (for multipart uploads). - **file** (Blob | File) - Required - The file content. - **name** (string) - Optional - The form field name for the file. - **method** (string) - Optional - HTTP method (POST or PUT). Defaults to POST for multipart, PUT for binary. - **uploadType** (string) - Optional - 'binary' or 'multipart'. Defaults to 'multipart' for POST, 'binary' for PUT. - **headers** (object) - Optional - Custom headers for the request. - **params** (object) - Optional - Form parameters for multipart uploads. - **maxRetries** (number) - Optional - Maximum number of retries for failed uploads. Defaults to 3. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the upload operation. #### Response Example ```json { "id": "a1b2c3d4e5f6" } ``` ``` -------------------------------- ### Preventing Missing Required Parameters in startUpload Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/errors.md Demonstrates how to correctly provide either `filePath` or a `files` array to avoid the 'Missing required parameter' error. ```typescript await Uploader.startUpload({ serverUrl: 'https://example.com/upload', headers: {} }); ``` ```typescript await Uploader.startUpload({ filePath: 'file:///path/to/file.jpg', serverUrl: 'https://example.com/upload', headers: {} }); ``` ```typescript await Uploader.startUpload({ files: [ { filePath: 'file:///path/to/file.jpg' } ], serverUrl: 'https://example.com/upload', headers: {} }); ``` -------------------------------- ### Failed Event Example Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Example of an UploadEvent object signifying a failed upload with an error message and status code. ```typescript const event: UploadEvent = { name: 'failed', id: 'abc123xyz', payload: { error: 'Network timeout', statusCode: 504 } }; ``` -------------------------------- ### Publish the Plugin Source: https://github.com/cap-go/capacitor-uploader/blob/main/CONTRIBUTING.md Execute this command to publish the plugin to the npm registry. A pre-publish hook ensures the plugin is prepared before publishing. ```shell npm publish ``` -------------------------------- ### uploadOption Interface Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Configuration options for initiating a file upload. This is the primary options object passed to `UploaderPlugin.startUpload()`. ```APIDOC ## uploadOption ### Description Configuration options for initiating a file upload. This is the primary options object passed to `UploaderPlugin.startUpload()`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **filePath** (string) - Optional - The local file path or URL of the file to upload. Can be a `file://` URL, absolute path, or HTTP(S) URL. Not required if `files` array is provided. Cannot be used together with `files` in binary uploads. - **files** (UploadFileOption[]) - Optional - Array of files to upload in a single multipart request. Each file can have its own field name and MIME type. Not supported for PUT (binary) uploads. Cannot be combined with `filePath` for binary uploads. - **serverUrl** (string) - **Yes** - The endpoint URL where the file should be uploaded. Must be a valid HTTP or HTTPS URL. - **notificationTitle** (string) - Optional - The title shown in the upload notification (Android only). Ignored on other platforms. Defaults to `'Uploading'`. - **headers** ({ [key: string]: string }) - **Yes** - HTTP headers to include in the upload request. Useful for authentication (e.g., `Authorization: Bearer token`), custom headers, content negotiation, etc. - **method** ('PUT' | 'POST') - Optional - The HTTP method to use. `PUT` is typically used for presigned S3 URLs or RESTful APIs. `POST` is standard for form submissions. Defaults to `'POST'`. - **mimeType** (string) - Optional - The MIME type of the file (e.g., `'image/jpeg'`, `'application/pdf'`, `'video/mp4'`). If not provided, the plugin attempts to determine it automatically based on the file extension or blob type. - **parameters** ({ [key: string]: string }) - Optional - Additional form fields to include in multipart uploads. These are sent as form parameters alongside the file. Ignored for binary uploads. - **maxRetries** (number) - Optional - The maximum number of times to retry the upload if it fails. Retries only occur on network/server errors, not on successful responses. Defaults to `0`. - **uploadType** ('binary' | 'multipart') - Optional - The encoding format for the upload. `'binary'` sends raw file bytes in the request body; `'multipart'` uses `multipart/form-data` encoding. Default: `'binary'` for PUT, `'multipart'` for POST. - **fileField** (string) - Optional - The form field name for the file in multipart uploads. Used when `uploadType` is `'multipart'` and no explicit `fieldName` is provided in the `files` array. Defaults to `'file'`. ### Request Example ```json { "filePath": "file:///path/to/file.jpg", "serverUrl": "https://api.example.com/upload", "headers": {} } ``` ### Response #### Success Response (200) This interface does not define a specific response structure. The success response depends on the server's implementation. #### Response Example ```json { "message": "Upload successful" } ``` ``` -------------------------------- ### Cancel Upload Pattern Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Demonstrates starting an upload and then cancelling it later using its ID. ```typescript const { id } = await Uploader.startUpload({...}); // ... later await Uploader.removeUpload({ id }); ``` -------------------------------- ### Handling Missing Required Parameters in startUpload Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/errors.md Shows how to catch and handle the 'Missing required parameter' error when calling `startUpload`. ```typescript try { await Uploader.startUpload({ serverUrl: 'https://example.com/upload', headers: {} // Missing filePath or files }); } catch (error) { if ((error as Error).message.includes('Missing required parameter')) { console.error('You must provide either filePath or files array'); } } ``` -------------------------------- ### Custom MIME Type Pattern Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Example of explicitly setting a custom MIME type for the upload. ```typescript const { id } = await Uploader.startUpload({ filePath: 'file:///path/to/file', serverUrl: 'https://api.example.com/upload', headers: {}, mimeType: 'application/octet-stream' }); ``` -------------------------------- ### Uploader.startUpload Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-web.md Initiates a file upload. Requires at least a filePath or file data, a server URL, and HTTP method. Supports custom parameters and retry configurations. ```APIDOC ## Uploader.startUpload ### Description Initiates a file upload. Requires at least a filePath or file data, a server URL, and HTTP method. Supports custom parameters and retry configurations. ### Method ```typescript await Uploader.startUpload(options: { filePath?: string; serverUrl: string; method?: 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'CONNECT' | 'TRACE' | 'PATCH'; uploadType?: 'multipart' | 'file'; parameters?: { [key: string]: any }; maxRetries?: number; headers?: { [key: string]: string }; }); ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **filePath** (string) - Optional - The path to the file to upload. Can be a system path, HTTP(S) URL, or IndexedDB path. - **serverUrl** (string) - Required - The URL of the server endpoint to upload to. - **method** (string) - Optional - The HTTP method to use for the upload. Defaults to 'POST'. - **uploadType** (string) - Optional - The type of upload. Defaults to 'multipart'. - **parameters** (object) - Optional - Additional parameters to send with the upload request. - **maxRetries** (number) - Optional - The maximum number of retries for failed uploads. - **headers** (object) - Optional - Custom headers to include in the upload request. ### Request Example ```json { "example": "await Uploader.startUpload({\n filePath: 'file:///Documents/photo.jpg',\n serverUrl: 'https://api.example.com/upload',\n method: 'POST',\n uploadType: 'multipart',\n parameters: { userId: '123' },\n maxRetries: 3\n});" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the initiated upload. #### Response Example ```json { "id": "unique-upload-id-123" } ``` ``` -------------------------------- ### Retry on Failure Pattern Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Example of configuring automatic retries for an upload. The plugin will retry up to the specified maxRetries on error. ```typescript const { id } = await Uploader.startUpload({ filePath: 'file:///path/to/file.jpg', serverUrl: 'https://api.example.com/upload', headers: {}, maxRetries: 3 // Automatically retry up to 3 times on error }); ``` -------------------------------- ### Handling File Not Found Error Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/errors.md Shows how to catch and handle the 'File not found' error when `startUpload` is called with an invalid or inaccessible file path. ```typescript try { await Uploader.startUpload({ filePath: userProvidedPath, serverUrl: 'https://example.com/upload', headers: {} }); } catch (error) { if ((error as Error).message === 'File not found') { console.error('The file does not exist at the specified path'); showErrorToUser('Please select a valid file'); } } ``` -------------------------------- ### Get Plugin Version Source: https://github.com/cap-go/capacitor-uploader/blob/main/README.md Retrieves the native Capacitor plugin version. This method returns a promise that resolves with the version string. ```typescript getPluginVersion() => Promise<{ version: string; }> ``` -------------------------------- ### Get Uploader Plugin Version Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-plugin.md Retrieve the version of the native Uploader plugin implementation. This is useful for compatibility checks or debugging. ```typescript const { version } = await Uploader.getPluginVersion(); console.log('Uploader plugin version:', version); if (version < '8.0.0') { console.warn('Plugin version is outdated'); } ``` -------------------------------- ### Complete IndexedDB Upload Workflow Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/path-helper.md Demonstrates the full process of storing a file in IndexedDB and then uploading it using the Capacitor Uploader with a semantic path. ```typescript // Example: Complete workflow for uploading from IndexedDB // 1. Store a file in IndexedDB import { openDB } from 'idb'; const db = await openDB('myapp'); const blob = new Blob(['file content'], { type: 'image/jpeg' }); await db.put('files', blob, 'photo-123'); // 2. Upload using the semantic path import { Uploader } from '@capgo/capacitor-uploader'; const { id } = await Uploader.startUpload({ filePath: 'idb://myapp/files/photo-123', serverUrl: 'https://api.example.com/upload', method: 'POST' }); // 3. Listen for completion Uploader.addListener('events', (event) => { if (event.name === 'completed') { console.log('File uploaded successfully'); } }); ``` -------------------------------- ### Get Plugin Version Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-web.md Retrieves the version identifier for the web plugin implementation. This method always returns '{ version: 'web' }'. ```typescript const versionInfo = await Uploader.getPluginVersion(); console.log('Uploader plugin version:', versionInfo.version); ``` -------------------------------- ### Format Code Source: https://github.com/cap-go/capacitor-uploader/blob/main/AGENTS.md Formats the project code using ESLint, Prettier, and SwiftLint. This command automatically fixes code style issues. ```bash bun run fmt ``` -------------------------------- ### Multipart Upload with Form Parameters Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Sets up a multipart upload using POST, specifying a custom file field, MIME type, authorization headers, and additional form parameters. ```typescript const uploadOption: uploadOption = { filePath: 'file:///photos/vacation.jpg', serverUrl: 'https://api.example.com/photos', method: 'POST', uploadType: 'multipart', fileField: 'photo', mimeType: 'image/jpeg', headers: { 'Authorization': 'Bearer token123' }, parameters: { 'album_id': '456', 'description': 'Vacation photo', 'tags': 'beach,sunset' }, maxRetries: 2, notificationTitle: 'Uploading Photo' }; ``` -------------------------------- ### Wrap startUpload in Try-Catch Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/errors.md Always enclose `Uploader.startUpload()` calls within a try-catch block to gracefully handle potential errors during upload initiation, such as network issues or invalid server URLs. ```typescript async function uploadFile(filePath: string) { try { const { id } = await Uploader.startUpload({ filePath, serverUrl: 'https://api.example.com/upload', headers: { 'Authorization': `Bearer ${token}` } }); console.log('Upload initiated with ID:', id); } catch (error) { console.error('Failed to start upload:', error); handleInitializationError(error); } } ``` -------------------------------- ### Multipart Upload with Multiple Files and Parameters Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-web.md Demonstrates a multipart upload with multiple files and additional form parameters. This is the default for POST requests. ```typescript const result = await Uploader.startUpload({ url: 'https://example.com/upload', files: [ { filePath: 'idb://my-db/my-files/file1.txt', name: 'file1.txt', fieldName: 'file1' }, { filePath: 'idb://my-db/my-files/file2.jpg', name: 'image.jpg', fieldName: 'photo' }, ], params: { userId: '123', authToken: 'abc', }, // uploadType: 'multipart' // Explicitly set or default for POST }); console.log('Multipart upload started with ID:', result.id); ``` -------------------------------- ### Integrate PathHelper with UploaderWeb Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/path-helper.md Demonstrates a workflow where PathHelper is used to parse an IndexedDB path, retrieve a blob from IndexedDB, and then upload it using the Uploader plugin. ```typescript // PathHelper is used internally by UploaderWeb when uploading files // from IndexedDB. Example workflow: // 1. Check if path is an IDB path if (PathHelper.isIndexedDBPath(filePath)) { // 2. Parse the path to get database, store, and key const { database, storeName, key } = PathHelper.parseIndexedDBPath(filePath); // 3. Use the parsed components to retrieve the blob from IndexedDB const db = await openDB(database); const blob = await db.get(storeName, key); // 4. Upload the blob via the Uploader plugin const { id } = await Uploader.startUpload({ filePath: 'idb://mydb/files/doc123', serverUrl: 'https://api.example.com/upload' }); } ``` -------------------------------- ### Clean Up Event Listeners Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/errors.md Demonstrates how to start monitoring events with a listener and properly remove it to prevent memory leaks. Ensure the listener is removed during component unmount or application teardown. ```typescript let listener: PluginListenerHandle | null = null; async function startMonitoring() { listener = await Uploader.addListener('events', (event) => { console.log(event); }); } async function stopMonitoring() { if (listener) { await listener.remove(); listener = null; } } // Call stopMonitoring in cleanup/teardown ``` -------------------------------- ### Upload Video Recorded with Camera Preview Source: https://github.com/cap-go/capacitor-uploader/blob/main/README.md Records a video using CameraPreview, then uploads the recorded file using the Uploader plugin. It includes event listeners to track upload progress, completion, or failure. ```typescript import { CameraPreview } from '@capgo/camera-preview' import { Uploader } from '@capgo/capacitor-uploader'; async function record() { await CameraPreview.startRecordVideo({ storeToFile: true }) await new Promise(resolve => setTimeout(resolve, 5000)) const fileUrl = await CameraPreview.stopRecordVideo() console.log(fileUrl.videoFilePath) await uploadVideo(fileUrl.videoFilePath) } async function uploadVideo(filePath: string) { Uploader.addListener('events', (event) => { switch (event.name) { case 'uploading': console.log(`Upload progress: ${event.payload.percent}%`); break; case 'completed': console.log('Upload completed successfully'); console.log('Server response status code:', event.payload.statusCode); break; case 'failed': console.error('Upload failed:', event.payload.error); break; } }); try { const result = await Uploader.startUpload({ filePath, serverUrl: 'S#_PRESIGNED_URL', method: 'PUT', headers: { 'Content-Type': 'video/mp4', }, mimeType: 'video/mp4', }); console.log('Video uploaded successfully:', result.id); } catch (error) { console.error('Error uploading video:', error); throw error; } } ``` -------------------------------- ### addListener('events', ...) Source: https://github.com/cap-go/capacitor-uploader/blob/main/README.md Listens for upload progress and status events. Events are fired for upload progress updates, completion, and failure. ```APIDOC ## addListener('events', ...) ### Description Listen for upload progress and status events. Events are fired for: Upload progress updates (with percent), Upload completion (with statusCode), Upload failure (with error and statusCode). ### Method ```typescript addListener(eventName: 'events', listenerFunc: (state: UploadEvent) => void) => Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **`eventName`** ('events') - Required - Must be 'events' - **`listenerFunc`** ((state: UploadEvent) => void) - Required - Callback function to handle upload events ### Request Example ```javascript Uploader.addListener('events', (event) => { switch (event.name) { case 'uploading': console.log(`Upload progress: ${event.payload.percent}%`); break; case 'completed': console.log('Upload completed successfully'); console.log('Server response status code:', event.payload.statusCode); break; case 'failed': console.error('Upload failed:', event.payload.error); break; } }); ``` ### Response #### Success Response (200) - **`value`** (PluginListenerHandle) - A handle to the listener that can be used to remove it. #### Response Example ```json { "value": { /* PluginListenerHandle object */ } } ``` ``` -------------------------------- ### UploaderPlugin Interface Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/overview.md The Capacitor Uploader plugin exposes a core interface with methods to manage file uploads. These include starting uploads, canceling them, listening for events, and retrieving the plugin version. ```APIDOC ## UploaderPlugin Interface ### Description The `Uploader` instance provides the primary interface for interacting with the Capacitor Uploader plugin. It allows users to initiate file uploads, cancel ongoing uploads, register for upload lifecycle events, and query the plugin's version. ### Methods - **`startUpload(options)`** - **Purpose**: Initiates a file upload process. - **Parameters**: `options` (uploadOption) - Configuration object for the upload. - **Returns**: A Promise that resolves with an object containing the unique `id` for the upload. - **`removeUpload(options)`** - **Purpose**: Cancels an ongoing or pending upload. - **Parameters**: `options` - An object containing the `id` of the upload to remove. - **`addListener(eventName, callback)`** - **Purpose**: Registers a listener for upload lifecycle events. - **Parameters**: - `eventName` (string): The name of the event to listen for (e.g., 'events'). - `callback` (function): The function to execute when the event is triggered. It receives `UploadEvent` data. - **Returns**: A `PluginListenerHandle` to manage the listener. - **`getPluginVersion()`** - **Purpose**: Retrieves the current version of the Capacitor Uploader plugin. - **Returns**: A string representing the plugin version. ``` -------------------------------- ### Full Plugin Verification Source: https://github.com/cap-go/capacitor-uploader/blob/main/AGENTS.md Performs a full verification of the plugin across iOS, Android, and Web platforms. This command should be run before submitting work. ```bash bun run verify ``` -------------------------------- ### Log Uploader Plugin Version on Initialization Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/api-reference/uploader-plugin.md Log the Uploader plugin version during application startup for debugging purposes. Includes error handling for cases where version retrieval might fail. ```typescript async function initializeUploader() { try { const { version } = await Uploader.getPluginVersion(); console.debug(`Running Capacitor Uploader v${version}`); } catch (error) { console.error('Failed to get plugin version:', error); } } ``` -------------------------------- ### uploadOption Interface Definition Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Defines the configuration options for initiating a file upload. This is the primary options object passed to `UploaderPlugin.startUpload()`. ```typescript export interface uploadOption { filePath?: string; files?: UploadFileOption[]; serverUrl: string; notificationTitle?: string; headers: { [key: string]: string; }; method?: 'PUT' | 'POST'; mimeType?: string; parameters?: { [key: string]: string }; maxRetries?: number; uploadType?: 'binary' | 'multipart'; fileField?: string; } ``` -------------------------------- ### Preventing Binary Upload with Multiple Files Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/errors.md Illustrates the correct approach for uploading multiple files using POST with multipart, and single files using PUT for binary uploads. ```typescript await Uploader.startUpload({ files: [ { filePath: 'file:///file1.jpg' }, { filePath: 'file:///file2.jpg' } ], serverUrl: 'https://s3.amazonaws.com/bucket/key', method: 'PUT', headers: {} }); ``` ```typescript await Uploader.startUpload({ files: [ { filePath: 'file:///file1.jpg' }, { filePath: 'file:///file2.jpg' } ], serverUrl: 'https://api.example.com/upload', method: 'POST', uploadType: 'multipart', headers: {} }); ``` ```typescript await Uploader.startUpload({ filePath: 'file:///file.jpg', serverUrl: 'https://s3.amazonaws.com/bucket/key', method: 'PUT', headers: {} }); ``` -------------------------------- ### uploadOption Interface Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/quick-reference.md Defines the options for initiating an upload. Includes file paths, server URL, headers, and upload method. ```typescript interface uploadOption { filePath?: string; files?: UploadFileOption[]; serverUrl: string; headers: { [key: string]: string }; method?: 'PUT' | 'POST'; mimeType?: string; parameters?: { [key: string]: string }; uploadType?: 'binary' | 'multipart'; fileField?: string; notificationTitle?: string; maxRetries?: number; } ``` -------------------------------- ### Handling Upload Events in Listener Source: https://github.com/cap-go/capacitor-uploader/blob/main/_autodocs/types.md Demonstrates how to register an event listener and process different types of UploadEvents, updating UI and handling success/failure. ```typescript Uploader.addListener('events', (event: UploadEvent) => { console.log(`Upload ${event.id}:`, event.name); if (event.name === 'uploading') { updateProgressBar(event.payload.percent || 0); } else if (event.name === 'completed') { console.log(`Success: HTTP ${event.payload.statusCode}`); handleUploadSuccess(event.id); } else if (event.name === 'failed') { console.error(`Error: ${event.payload.error}`); handleUploadFailure(event.id, event.payload.error); } }); ```