### Run Example App with npm start Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/example-app/README.md Use this command to run the example application. Ensure you have the necessary dependencies installed. ```bash npm start ``` -------------------------------- ### Install @capacitor/file-transfer Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/README.md Install the plugin and sync Capacitor to include native project changes. ```bash npm install @capacitor/file-transfer npx cap sync ``` -------------------------------- ### Install Dependencies Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/CONTRIBUTING.md Install the necessary Node.js dependencies for the plugin. ```shell npm install ``` -------------------------------- ### Install SwiftLint (macOS) Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/CONTRIBUTING.md Install SwiftLint using Homebrew if you are developing on macOS for Swift code linting. ```shell brew install swiftlint ``` -------------------------------- ### Upload File Using Blob on Web Source: https://context7.com/ionic-team/capacitor-file-transfer/llms.txt This example shows how to upload a file on the web platform by passing a `Blob` object directly. The `path` option is used for the filename in the FormData, and `blob` is used for the file content. This bypasses filesystem resolution on web. ```typescript import { FileTransfer } from '@capacitor/file-transfer'; async function uploadSelectedFile(inputFile: File) { try { const result = await FileTransfer.uploadFile({ url: 'https://api.example.com/upload', path: inputFile.name, // used as FormData filename blob: inputFile, // web-only: use Blob directly fileKey: 'attachment', progress: true, headers: { Authorization: 'Bearer MY_TOKEN', }, }); console.log(`Uploaded ${result.bytesSent} bytes — status ${result.responseCode}`); return JSON.parse(result.response ?? '{}'); } catch (error: any) { console.error(`Upload failed [${error.code}]: ${error.message}`); throw error; } } // Wire to an element document.getElementById('file-input')?.addEventListener('change', (event) => { const file = (event.target as HTMLInputElement).files?.[0]; if (file) uploadSelectedFile(file); }); ``` -------------------------------- ### Handle File Transfer Errors Source: https://context7.com/ionic-team/capacitor-file-transfer/llms.txt This example demonstrates how to handle potential errors during file transfers using a predefined error message map. It also shows how to access additional HTTP details from `error.data` on native platforms for specific error codes like 'OS-PLUG-FLTR-0010'. ```typescript import { FileTransfer, FileTransferError } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; const ERROR_MESSAGES: Record = { 'OS-PLUG-FLTR-0004': 'Invalid input parameters', 'OS-PLUG-FLTR-0005': 'Invalid or empty server URL', 'OS-PLUG-FLTR-0006': 'Permission denied', 'OS-PLUG-FLTR-0007': 'File not found', 'OS-PLUG-FLTR-0008': 'Failed to connect to server', 'OS-PLUG-FLTR-0009': 'Server returned HTTP 304 Not Modified', 'OS-PLUG-FLTR-0010': 'Server returned an HTTP error status', 'OS-PLUG-FLTR-0011': 'Generic operation failure', }; async function robustDownload(remoteUrl: string, localPath: string) { try { const result = await FileTransfer.downloadFile({ url: remoteUrl, path: localPath }); return result; } catch (error: any) { const friendlyMsg = ERROR_MESSAGES[error.code] ?? 'Unknown error'; console.error(`[${error.code}] ${friendlyMsg}: ${error.message}`); if (error.code === 'OS-PLUG-FLTR-0010' && error.data) { // FileTransferError available on native platforms const { httpStatus, body, headers, source, target, exception } = error.data as FileTransferError; console.error({ httpStatus, body, headers, source, target, exception }); } throw error; } } ``` -------------------------------- ### Navigate to Plugin Directory Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/CONTRIBUTING.md Change the current directory to the plugin's package folder to begin development. ```shell cd packages/capacitor-plugin ``` -------------------------------- ### Download File with Progress Tracking Source: https://context7.com/ionic-team/capacitor-file-transfer/llms.txt Download a file from a URL to the device filesystem, with options for headers, parameters, timeouts, and progress events. Requires Filesystem plugin for native path resolution. Progress events are throttled on native platforms. ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; // Resolve a native file URI for the download destination const { uri } = await Filesystem.getUri({ directory: Directory.Data, path: 'reports/annual-report-2024.pdf', }); // Start listening for progress before calling downloadFile const progressHandle = await FileTransfer.addListener('progress', (progress) => { if (progress.type === 'download' && progress.lengthComputable) { const pct = Math.round((progress.bytes / progress.contentLength) * 100); console.log(`Download: ${pct}% (${progress.bytes}/${progress.contentLength} bytes)`); } }); try { const result = await FileTransfer.downloadFile({ url: 'https://api.example.com/reports/annual-report-2024.pdf', path: uri, progress: true, // emit progress events method: 'GET', // default; explicit here for clarity headers: { Authorization: 'Bearer MY_ACCESS_TOKEN', Accept: 'application/pdf', }, params: { version: '2', }, connectTimeout: 30000, // 30 s connection timeout readTimeout: 60000, // 60 s read timeout disableRedirects: false, shouldEncodeUrlParams: true, }); // result.path — native file path where the file was saved // result.blob — Blob (web only) console.log('Downloaded to:', result.path); } catch (error: any) { if (error.code === 'OS-PLUG-FLTR-0010') { // HTTP-level error (4xx/5xx) — inspect FileTransferError fields const detail = error.data; console.error(`HTTP ${detail.httpStatus}: ${detail.body}`); console.error('Source URL:', detail.source); console.error('Target path:', detail.target); console.error('Response headers:', detail.headers); } else { // Network, permission, or generic error console.error(`Error [${error.code}]: ${error.message}`); } } finally { await progressHandle.remove(); // clean up listener } ``` -------------------------------- ### Build Plugin and API Docs Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/CONTRIBUTING.md Builds the plugin's web assets and generates API documentation using @capacitor/docgen. This compiles TypeScript to ESM JavaScript and bundles it for different environments. ```shell npm run build ``` -------------------------------- ### Download File with Capacitor Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/README.md Download a file from a URL to a local path. Ensure the file path is obtained using the Filesystem plugin first. Progress events can be listened to for download status. ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; // First get the full file path using Filesystem const fileInfo = await Filesystem.getUri({ directory: Directory.Data, path: 'downloaded-file.pdf' }); try { // Then use the FileTransfer plugin to download await FileTransfer.downloadFile({ url: 'https://example.com/file.pdf', path: fileInfo.uri, progress: true }); } catch(error) { if (error.code === 'OS-PLUG-FLTR-0010') { // HTTP error - see `FileTransferError` for details on fields available in `errorData` let errorData = error.data; } else { // other errors - use `error.code` and `error.message` for more information. } } // Progress events FileTransfer.addListener('progress', (progress) => { console.log(`Downloaded ${progress.bytes} of ${progress.contentLength}`); }); ``` -------------------------------- ### DownloadFileOptions Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Options for configuring file downloads. ```APIDOC ## DownloadFileOptions ### Description Options for configuring file downloads. ### Properties - **`url`** (string) - Required - The URL to download the file from. - **`path`** (string) - Required - The full file path the downloaded file should be moved to. You may use a plugin like `@capacitor/filesystem` to get a complete file path. - **`progress`** (boolean) - Optional - If true, progress event will be dispatched on every chunk received. Default is `false`. - **`method`** (string) - Optional - The Http Request method to run. (Default is GET) - **`params`** (HttpParams) - Optional - URL parameters to append to the request. This `HttpParams` interface comes from `@capacitor/core`. - **`headers`** (HttpHeaders) - Optional - Http Request headers to send with the request. This `HttpHeaders` interface comes from `@capacitor/core`. - **`readTimeout`** (number) - Optional - How long to wait to read additional data in milliseconds. Default is 60,000 milliseconds (1 minute). Not supported on web. - **`connectTimeout`** (number) - Optional - How long to wait for the initial connection in milliseconds. Default is 60,000 milliseconds (1 minute). Not supported on web. - **`disableRedirects`** (boolean) - Optional - Sets whether automatic HTTP redirects should be disabled. - **`shouldEncodeUrlParams`** (boolean) - Optional - Use this option if you need to keep the URL unencoded in certain cases. The default is `true`. Not supported on web. ``` -------------------------------- ### Verify Web and Native Projects Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/CONTRIBUTING.md Builds and validates both the web and native projects. This script is used in CI to ensure the plugin builds correctly across all platforms. ```shell npm run verify ``` -------------------------------- ### addListener('progress', listenerFunc) Source: https://context7.com/ionic-team/capacitor-file-transfer/llms.txt Subscribes to transfer progress events, providing real-time updates on upload or download status. ```APIDOC ## addListener('progress', listenerFunc) ### Description Registers a callback that is invoked whenever a progress update is fired during an active download or upload. On Android and iOS, updates are throttled to at most one event per 100 ms to avoid performance degradation. The `ProgressStatus` payload includes the transfer type, URL, bytes transferred, total content length, and a flag indicating whether the total is computable. ### Parameters #### Path Parameters - **event** (string) - Required - The event name, must be 'progress'. - **listenerFunc** (function) - Required - The callback function to execute when the progress event fires. ### Listener Payload (`ProgressStatus`) - **type** (string) - 'download' | 'upload' - **url** (string) - URL associated with the transfer. - **bytes** (number) - Bytes transferred so far. - **contentLength** (number) - Total byte count. - **lengthComputable** (boolean) - False when server omits Content-Length header. ### Request Example ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import type { PluginListenerHandle } from '@capacitor/core'; let progressHandle: PluginListenerHandle; async function startMonitoring() { progressHandle = await FileTransfer.addListener('progress', (progress) => { if (progress.lengthComputable) { const percentage = ((progress.bytes / progress.contentLength) * 100).toFixed(1); updateProgressBar(progress.type, parseFloat(percentage)); } else { console.log(`${progress.type}: ${progress.bytes} bytes (total unknown)`); } }); } function updateProgressBar(type: 'download' | 'upload', pct: number) { const bar = document.getElementById(`${type}-progress`) as HTMLProgressElement; if (bar) bar.value = pct; } async function stopMonitoring() { await progressHandle.remove(); } ``` ``` -------------------------------- ### Upload File with Capacitor Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/README.md Upload a local file to a URL. The file path should be obtained using the Filesystem plugin. Chunked mode and custom headers can be configured. Note that 'multipart/form-data' is the default content type unless overridden. ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; // First get the full file path using Filesystem const fileInfo = await Filesystem.getUri({ directory: Directory.Cache, path: 'image_upload.png' }); try { // Then use the FileTransfer plugin to upload const result = await FileTransfer.uploadFile({ url: 'https://example.com/upload_api', path: fileInfo.uri, chunkedMode: true, headers: { // Upload uses `multipart/form-data` by default. // If you want to avoid that, you can set the 'Content-Type' header explicitly. 'Content-Type': 'application/octet-stream', }, progress: false }); // get server response and other info from result - see `UploadFileResult` interface } catch(error) { if (error.code === 'OS-PLUG-FLTR-0010') { // HTTP error - see `FileTransferError` for details on fields available in `errorData` let errorData = error.data; } else { // other errors - use `error.code` and `error.message` for more information. } } ``` -------------------------------- ### UploadFileOptions Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Configuration options for uploading files. ```APIDOC ## UploadFileOptions ### Description Options for configuring file uploads. ### Properties - **`url`** (string) - Required - The URL to upload the file to. - **`path`** (string) - Required - Full file path of the file to upload. You may use a plugin like `@capacitor/filesystem` to get a complete file path. - **`blob`** (Blob) - Optional - Blob data to upload. Will use this instead of path if provided. This is only available on web. - **`chunkedMode`** (boolean) - Optional - Whether to upload data in a chunked streaming mode. Not supported on web. Note: The upload uses `Content-Type: multipart/form-data`, when `chunkedMode` is `true`. Depending on your backend server, this can cause the upload to fail. If your server expects a raw stream (e.g. `application/octet-stream`), you must explicitly set the `Content-Type` header in `headers`. - **`mimeType`** (string) - Optional - Mime type of the data to upload. Only used if "Content-Type" header was not provided. - **`fileKey`** (string) - Optional - Type of form element. The default is set to "file". Only used if "Content-Type" header was not provided. - **`progress`** (boolean) - Optional - If true, progress event will be dispatched on every chunk received. See addListener() for more information. Chunks are throttled to every 100ms on Android/iOS to avoid slowdowns. Default is `false`. - **`method`** (string) - Optional - The Http Request method to run. (Default is POST) ``` -------------------------------- ### uploadFile Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Initiates a file upload to a specified server. It returns a promise that resolves with upload details or rejects with a `FileTransferError` on HTTP errors. ```APIDOC ## uploadFile ### Description Perform an HTTP request to upload a file to a server. If the server returns an HTTP error (e.g. 404, 500, etc.), the promise will be rejected. To get information about the HTTP error response when running Android and iOS (not applicable to web), use the `FileTransferError` interface available at `error.data` attribute. ### Method ```typescript uploadFile(options: UploadFileOptions) => Promise ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **`options`** (UploadFileOptions) - Required - Configuration for the file upload. ### Request Example ```json { "example": "// Example usage not provided in source" } ``` ### Response #### Success Response (200) - **`UploadFileResult`** - An object containing details about the upload. #### Response Example ```json { "example": "// Example response not provided in source" } ``` ``` -------------------------------- ### UploadFileOptions Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Options for configuring file uploads. These parameters allow customization of HTTP requests, including URL parameters, headers, and timeouts. ```APIDOC ## UploadFileOptions ### Description Options for configuring file uploads. These parameters allow customization of HTTP requests, including URL parameters, headers, and timeouts. ### Parameters #### Request Body Fields - **`params`** (`HttpParams`) - URL parameters to append to the request. This `HttpParams` interface comes from `@capacitor/core`. - **`headers`** (`HttpHeaders`) - Http Request headers to send with the request. This `HttpHeaders` interface comes from `@capacitor/core`. - **`readTimeout`** (`number`) - How long to wait to read additional data in milliseconds. Resets each time new data is received. Default is 60,000 milliseconds (1 minute). Not supported on web. - **`connectTimeout`** (`number`) - How long to wait for the initial connection in milliseconds. Default is 60,000 milliseconds (1 minute). Not supported on web. In iOS, there's no real distinction between `connectTimeout` and `readTimeout`. Plugin tries to use `connectTimeout`, if not uses `readTimeout`, if not uses default. - **`disableRedirects`** (`boolean`) - Sets whether automatic HTTP redirects should be disabled. Not supported on web. - **`shouldEncodeUrlParams`** (`boolean`) - Use this option if you need to keep the URL unencoded in certain cases (already encoded, azure/firebase testing, etc.). The default is `true`. Not supported on web. ``` -------------------------------- ### downloadFile Source: https://context7.com/ionic-team/capacitor-file-transfer/llms.txt Downloads a file from a specified URL to a local path on the device. Supports progress events, custom headers, query parameters, and timeouts. ```APIDOC ## downloadFile(options) ### Description Performs an HTTP GET (or custom method) request and saves the response body to the path specified by `options.path`. On Android/iOS, the path must be a fully-qualified native URI obtained from `@capacitor/filesystem`. On web, the file is written via the Filesystem plugin if available; otherwise a browser download is triggered and the raw `Blob` is returned. ### Method `FileTransfer.downloadFile` ### Parameters #### Options Object - **url** (string) - Required - The URL of the file to download. - **path** (string) - Required - The native file path where the file should be saved. Must be a fully-qualified URI on Android/iOS. - **progress** (boolean) - Optional - If true, emit progress events. - **method** (string) - Optional - The HTTP method to use (e.g., 'GET', 'POST'). Defaults to 'GET'. - **headers** (object) - Optional - An object containing custom HTTP headers. - **params** (object) - Optional - An object containing query parameters to append to the URL. - **connectTimeout** (number) - Optional - Connection timeout in milliseconds. - **readTimeout** (number) - Optional - Read timeout in milliseconds. - **disableRedirects** (boolean) - Optional - If true, do not follow HTTP redirects. - **shouldEncodeUrlParams** (boolean) - Optional - If true, encode URL parameters. ### Request Example ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; // Resolve a native file URI for the download destination const { uri } = await Filesystem.getUri({ directory: Directory.Data, path: 'reports/annual-report-2024.pdf', }); // Start listening for progress before calling downloadFile const progressHandle = await FileTransfer.addListener('progress', (progress) => { if (progress.type === 'download' && progress.lengthComputable) { const pct = Math.round((progress.bytes / progress.contentLength) * 100); console.log(`Download: ${pct}% (${progress.bytes}/${progress.contentLength} bytes)`) } }); try { const result = await FileTransfer.downloadFile({ url: 'https://api.example.com/reports/annual-report-2024.pdf', path: uri, progress: true, method: 'GET', headers: { Authorization: 'Bearer MY_ACCESS_TOKEN', Accept: 'application/pdf', }, params: { version: '2', }, connectTimeout: 30000, readTimeout: 60000, disableRedirects: false, shouldEncodeUrlParams: true, }); console.log('Downloaded to:', result.path); } catch (error: any) { if (error.code === 'OS-PLUG-FLTR-0010') { const detail = error.data; console.error(`HTTP ${detail.httpStatus}: ${detail.body}`); } else { console.error(`Error [${error.code}]: ${error.message}`); } } finally { await progressHandle.remove(); // clean up listener } ``` ### Response #### Success Response - **path** (string) - The native file path where the file was saved. - **blob** (Blob) - (Web only) The raw `Blob` data if Filesystem plugin is not available. #### Response Example ```json { "path": "file:///path/to/downloaded/file.pdf", "blob": "" } ``` ### Error Handling - **OS-PLUG-FLTR-0010**: HTTP-level error (e.g., 4xx/5xx). Inspect `error.data` for `httpStatus`, `body`, `source`, `target`, and `headers`. - Other codes indicate network, permission, or generic errors. Inspect `error.code` and `error.message`. ``` -------------------------------- ### Upload a local file to a server with Capacitor File Transfer Source: https://context7.com/ionic-team/capacitor-file-transfer/llms.txt Use this snippet to upload a local file to a server using HTTP POST. Configure options like URL, file path, chunked mode, MIME type, and headers. Progress tracking is enabled by default. ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; // Resolve the native URI of the file to upload const {uri} = await Filesystem.getUri({ directory: Directory.Cache, path: 'camera/photo_20240315.jpg', }); // Track upload progress await FileTransfer.addListener('progress', (progress) => { if (progress.type === 'upload') { const pct = progress.lengthComputable ? Math.round((progress.bytes / progress.contentLength) * 100) : '?'; console.log(`Upload: ${pct}% — ${progress.bytes} bytes sent to ${progress.url}`); } }); try { const result = await FileTransfer.uploadFile({ url: 'https://api.example.com/v1/media/upload', path: uri, chunkedMode: false, // set true to stream in chunks (multipart/form-data) mimeType: 'image/jpeg', // used when Content-Type header is not set explicitly fileKey: 'photo', // multipart form field name (default: "file") progress: true, headers: { Authorization: 'Bearer MY_ACCESS_TOKEN', // Uncomment to bypass multipart and send raw stream: // 'Content-Type': 'application/octet-stream', }, params: { albumId: '42', }, connectTimeout: 15000, readTimeout: 120000, // allow extra time for large uploads disableRedirects: false, shouldEncodeUrlParams: true, }); // result.bytesSent — total bytes sent // result.responseCode — HTTP status code string (e.g. "200") // result.response — response body text // result.headers — response headers map console.log(`Uploaded ${result.bytesSent} bytes, server responded ${result.responseCode}`); const serverPayload = JSON.parse(result.response ?? '{}'); console.log('Server response:', serverPayload); } catch (error: any) { if (error.code === 'OS-PLUG-FLTR-0010') { const detail = error.data; console.error(`HTTP ${detail.httpStatus}: ${detail.body}`); } else { console.error(`Error [${error.code}]: ${error.message}`); } } finally { await FileTransfer.removeAllListeners(); } ``` -------------------------------- ### uploadFile Source: https://context7.com/ionic-team/capacitor-file-transfer/llms.txt Performs an HTTP POST request to upload a local file to a server. Supports chunked mode and custom headers for flexible upload scenarios. ```APIDOC ## uploadFile(options) ### Description Performs an HTTP POST (or custom method) request that sends the file at `options.path` as `multipart/form-data` by default. When `chunkedMode` is `true`, data is streamed in chunks; override `Content-Type` to `application/octet-stream` if the server expects a raw body. On web, supply `options.blob` directly instead of a path (path-based upload on web requires `@capacitor/filesystem`). ### Parameters #### Path Parameters - **options.path** (string) - Required - The local path to the file to upload. - **options.url** (string) - Required - The URL to upload the file to. #### Query Parameters - **options.chunkedMode** (boolean) - Optional - If true, stream data in chunks (multipart/form-data). Defaults to false. - **options.mimeType** (string) - Optional - The MIME type of the file. Used when Content-Type header is not set explicitly. - **options.fileKey** (string) - Optional - The multipart form field name for the file. Defaults to "file". - **options.progress** (boolean) - Optional - If true, enable progress events. - **options.headers** (object) - Optional - Custom headers to send with the request. - **options.params** (object) - Optional - Additional parameters to send with the request. - **options.connectTimeout** (number) - Optional - Connection timeout in milliseconds. - **options.readTimeout** (number) - Optional - Read timeout in milliseconds. - **options.disableRedirects** (boolean) - Optional - If true, disable HTTP redirects. - **options.shouldEncodeUrlParams** (boolean) - Optional - If true, encode URL parameters. ### Request Example ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; const { uri } = await Filesystem.getUri({ directory: Directory.Cache, path: 'camera/photo_20240315.jpg', }); await FileTransfer.addListener('progress', (progress) => { if (progress.type === 'upload') { const pct = progress.lengthComputable ? Math.round((progress.bytes / progress.contentLength) * 100) : '?'; console.log(`Upload: ${pct}% — ${progress.bytes} bytes sent to ${progress.url}`); } }); try { const result = await FileTransfer.uploadFile({ url: 'https://api.example.com/v1/media/upload', path: uri, chunkedMode: false, mimeType: 'image/jpeg', fileKey: 'photo', progress: true, headers: { Authorization: 'Bearer MY_ACCESS_TOKEN', }, params: { albumId: '42', }, connectTimeout: 15000, readTimeout: 120000, disableRedirects: false, shouldEncodeUrlParams: true, }); console.log(`Uploaded ${result.bytesSent} bytes, server responded ${result.responseCode}`); const serverPayload = JSON.parse(result.response ?? '{}'); console.log('Server response:', serverPayload); } catch (error: any) { if (error.code === 'OS-PLUG-FLTR-0010') { const detail = error.data; console.error(`HTTP ${detail.httpStatus}: ${detail.body}`); } else { console.error(`Error [${error.code}]: ${error.message}`); } } finally { await FileTransfer.removeAllListeners(); } ``` ### Response #### Success Response (200) - **bytesSent** (number) - Total bytes sent. - **responseCode** (string) - HTTP status code string (e.g. "200"). - **response** (string) - Response body text. - **headers** (object) - Response headers map. #### Response Example ```json { "bytesSent": 1024, "responseCode": "200", "response": "{\"message\": \"File uploaded successfully\"}", "headers": { "Content-Type": "application/json" } } ``` ``` -------------------------------- ### Download File Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Performs an HTTP request to download a file from a given URL to a specified local path. It can optionally report progress and provides detailed error information for HTTP-related failures. ```APIDOC ## downloadFile ### Description Perform an HTTP request to a server and download the file to the specified destination. If the server returns an HTTP error (e.g. 404, 500, etc.), the promise will be rejected. To get information about the HTTP error response when running on Android and iOS (not applicable to web), use the `FileTransferError` interface available at `error.data` attribute. ### Method ```typescript downloadFile(options: DownloadFileOptions) => Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### `options` (`DownloadFileOptions`) - **`url`** (string) - Required - The URL to download the file from. - **`path`** (string) - Required - The local file path to save the downloaded file to. - **`progress`** (boolean) - Optional - If true, progress events will be emitted. ### Request Example ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; const fileInfo = await Filesystem.getUri({ directory: Directory.Data, path: 'downloaded-file.pdf' }); try { await FileTransfer.downloadFile({ url: 'https://example.com/file.pdf', path: fileInfo.uri, progress: true }); } catch(error) { console.error('Download failed:', error); } ``` ### Response #### Success Response (`DownloadFileResult`) - **`path`** (string) - The local path where the file was saved. #### Response Example ```json { "path": "file:///path/to/downloaded-file.pdf" } ``` ### Errors - **`OS-PLUG-FLTR-0010`**: HTTP error. `error.data` contains `httpStatus` and `body`. - Other errors: Use `error.code` and `error.message`. ``` -------------------------------- ### Upload File Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Uploads a file from a local path to a specified URL. Supports chunked mode, custom headers, and can optionally report progress. Error handling is provided for HTTP failures. ```APIDOC ## uploadFile ### Description Uploads a file from a local path to a specified URL. Supports chunked mode, custom headers, and can optionally report progress. Error handling is provided for HTTP failures. ### Method ```typescript uploadFile(options: UploadFileOptions) => Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### `options` (`UploadFileOptions`) - **`url`** (string) - Required - The URL to upload the file to. - **`path`** (string) - Required - The local file path of the file to upload. - **`chunkedMode`** (boolean) - Optional - If true, the upload will be performed in chunks. - **`headers`** (object) - Optional - Custom headers to send with the upload request. By default, uses `multipart/form-data`. Can be overridden by setting 'Content-Type'. - **`progress`** (boolean) - Optional - If true, progress events will be emitted. ### Request Example ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; const fileInfo = await Filesystem.getUri({ directory: Directory.Cache, path: 'image_upload.png' }); try { const result = await FileTransfer.uploadFile({ url: 'https://example.com/upload_api', path: fileInfo.uri, chunkedMode: true, headers: { 'Content-Type': 'application/octet-stream' }, progress: false }); console.log('Upload result:', result); } catch(error) { console.error('Upload failed:', error); } ``` ### Response #### Success Response (`UploadFileResult`) - **`response`** (object) - The server's response. - **`bytesSent`** (number) - The number of bytes sent during the upload. #### Response Example ```json { "response": { "data": "Success!", "status": 200 }, "bytesSent": 10240 } ``` ### Errors - **`OS-PLUG-FLTR-0010`**: HTTP error. `error.data` contains `httpStatus` and `body`. - Other errors: Use `error.code` and `error.message`. ``` -------------------------------- ### Progress Listener Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Listens for progress events during file downloads or uploads. Emits an event containing the number of bytes transferred and the total content length. ```APIDOC ## addListener('progress', ...) ### Description Listens for progress events during file downloads or uploads. Emits an event containing the number of bytes transferred and the total content length. ### Method ```typescript addListener(eventName: 'progress', listenerFunc: (progress: ProgressEvent) => void) => Promise & PluginListenerHandle ``` ### Parameters #### `eventName` ('progress') - **`eventName`** ('progress') - Required - The name of the event to listen for. #### `listenerFunc` (`(progress: ProgressEvent) => void`) - **`listenerFunc`** - Required - The callback function to execute when the progress event is fired. - **`progress`** (`ProgressEvent`) - **`bytes`** (number) - The number of bytes transferred so far. - **`contentLength`** (number) - The total size of the file in bytes. ### Request Example ```typescript import { FileTransfer } from '@capacitor/file-transfer'; FileTransfer.addListener('progress', (progress) => { console.log(`Downloaded ${progress.bytes} of ${progress.contentLength}`); }); ``` ### Response Returns a `PluginListenerHandle` object that can be used to remove the listener. ### Errors None explicitly documented for adding a listener. ``` -------------------------------- ### Subscribe to transfer progress events with Capacitor File Transfer Source: https://context7.com/ionic-team/capacitor-file-transfer/llms.txt Implement progress tracking for uploads or downloads by adding a listener. This snippet shows how to handle progress updates, including cases where the total content length is not computable. ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import type { PluginListenerHandle } from '@capacitor/core'; let progressHandle: PluginListenerHandle; async function startMonitoring() { progressHandle = await FileTransfer.addListener('progress', (progress) => { // progress.type — 'download' | 'upload' // progress.url — URL associated with the transfer // progress.bytes — bytes transferred so far // progress.contentLength — total byte count // progress.lengthComputable — false when server omits Content-Length header if (progress.lengthComputable) { const percentage = ((progress.bytes / progress.contentLength) * 100).toFixed(1); updateProgressBar(progress.type, parseFloat(percentage)); } else { console.log(`${progress.type}: ${progress.bytes} bytes (total unknown)`); } }); } function updateProgressBar(type: 'download' | 'upload', pct: number) { const bar = document.getElementById(`${type}-progress`) as HTMLProgressElement; if (bar) bar.value = pct; } // Remove a single listener when no longer needed async function stopMonitoring() { await progressHandle.remove(); } ``` -------------------------------- ### Download File with Capacitor File Transfer Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Download a file from a URL to a specified local path. Handles progress events and potential HTTP errors. ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; // First get the full file path using Filesystem const fileInfo = await Filesystem.getUri({ directory: Directory.Data, path: 'downloaded-file.pdf' }); try { // Then use the FileTransfer plugin to download await FileTransfer.downloadFile({ url: 'https://example.com/file.pdf', path: fileInfo.uri, progress: true }); } catch(error) { if (error.code === 'OS-PLUG-FLTR-0010') { // HTTP error - see `FileTransferError` for details on fields available in `errorData` let errorData = error.data; this.showError('Upload failed: ' + errorData.httpStatus + '; ' + errorData.body); } else { // other errors - use `error.code` and `error.message` for more information. this.showError('Upload failed: ' + error.code + '; ' + error.message); } } // Progress events FileTransfer.addListener('progress', (progress) => { console.log(`Downloaded ${progress.bytes} of ${progress.contentLength}`); }); ``` -------------------------------- ### Lint and Format Code Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/CONTRIBUTING.md Checks code formatting and quality, and attempts to auto-fix issues. The 'lint' command is used in CI. ```shell npm run lint ``` ```shell npm run fmt ``` -------------------------------- ### Error Codes Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md A list of common error codes returned by the file transfer plugin, along with their descriptions and supported platforms. ```APIDOC ## Errors The plugin returns specific error codes for various issues encountered during file transfer operations. Below is a table of common error codes: | Error code | Platform(s) | Description | |-------------------|-------------------|-----------------------------------------------------------------------------| | OS-PLUG-FLTR-0004 | Android, iOS | The method's input parameters aren't valid. | | OS-PLUG-FLTR-0005 | Android, iOS | Invalid server URL was provided or URL is empty. | | OS-PLUG-FLTR-0006 | Android, iOS | Unable to perform operation, user denied permission request. | | OS-PLUG-FLTR-0007 | Android, iOS | Operation failed because file does not exist. | | OS-PLUG-FLTR-0008 | Android, iOS, Web | Failed to connect to server. | | OS-PLUG-FLTR-0009 | Android, iOS | The server responded with HTTP 304 – Not Modified. Check HTTP caching headers. | | OS-PLUG-FLTR-0010 | Android, iOS | The server responded with an HTTP error status code. | | OS-PLUG-FLTR-0011 | Android, iOS, Web | The operation failed with an error (generic error). | When handling errors, you can inspect the `FileTransferError` object, which may contain additional details like `code`, `message`, `source`, `target`, `httpStatus`, `body`, and `headers`. ``` -------------------------------- ### ProgressStatus Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Represents the status of a file transfer operation, including type, URL, bytes transferred, and content length. ```APIDOC ## ProgressStatus ### Description Provides information about the progress of a file transfer operation (upload or download). ### Properties #### `type` - **`type`** ('download' | 'upload') - The type of transfer operation. #### `url` - **`url`** (string) - The URL of the file associated with the transfer. #### `bytes` - **`bytes`** (number) - The number of bytes transferred so far. #### `contentLength` - **`contentLength`** (number) - The total number of bytes associated with the file transfer. #### `lengthComputable` - **`lengthComputable`** (boolean) - Indicates whether the `contentLength` is available and relevant. ### Example ```typescript { type: 'upload', url: 'https://example.com/upload', bytes: 1024, contentLength: 5120, lengthComputable: true } ``` ``` -------------------------------- ### Upload File with Capacitor File Transfer Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Upload a local file to a specified URL. Supports chunked mode and custom headers. Handles potential HTTP errors. ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; // First get the full file path using Filesystem const fileInfo = await Filesystem.getUri({ directory: Directory.Cache, path: 'image_upload.png' }); try { // Then use the FileTransfer plugin to upload const result = await FileTransfer.uploadFile({ url: 'https://example.com/upload_api', path: fileInfo.uri, chunkedMode: true, headers: { // Upload uses `multipart/form-data` by default. // If you want to avoid that, you can set the 'Content-Type' header explicitly. 'Content-Type': 'application/octet-stream', }, progress: false }); // get server response and other info from result - see `UploadFileResult` interface } catch(error) { if (error.code === 'OS-PLUG-FLTR-0010') { // HTTP error - see `FileTransferError` for details on fields available in `errorData` let errorData = error.data; this.showError('Upload failed: ' + errorData.httpStatus + '; ' + errorData.body); } else { // other errors - use `error.code` and `error.message` for more information. this.showError('Upload failed: ' + error.code + '; ' + error.message); } } ``` -------------------------------- ### PluginListenerHandle Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Represents a handle to a plugin listener. It provides a method to remove the listener. ```APIDOC ## PluginListenerHandle ### Description A handle to a plugin listener that allows for its removal. ### Properties #### `remove` - **`remove`** (() => Promise<void>) - A function that, when called, removes the listener. ### Example ```typescript const listenerHandle = await SomePlugin.addListener('someEvent', () => { ... }); // To remove the listener later: await listenerHandle.remove(); ``` ``` -------------------------------- ### removeAllListeners Source: https://context7.com/ionic-team/capacitor-file-transfer/llms.txt Removes all event listeners attached to the File Transfer plugin to prevent memory leaks. ```APIDOC ## removeAllListeners() ### Description Removes every listener attached to the plugin. Call this when a component or page is destroyed to prevent memory leaks and stale callbacks. ### Request Example ```typescript import { FileTransfer } from '@capacitor/file-transfer'; async function onPageDestroy() { await FileTransfer.removeAllListeners(); console.log('All FileTransfer listeners removed.'); } ``` ``` -------------------------------- ### Remove All Listeners Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Removes all listeners for the FileTransfer plugin. This is useful for cleaning up resources when the component unmounts. ```APIDOC ## removeAllListeners() ### Description Removes all listeners for the FileTransfer plugin. This is useful for cleaning up resources when the component unmounts. ### Method ```typescript removeAllListeners() => Promise ``` ### Parameters None ### Request Example ```typescript import { FileTransfer } from '@capacitor/file-transfer'; await FileTransfer.removeAllListeners(); ``` ### Response Returns a Promise that resolves when all listeners have been removed. ### Errors None explicitly documented for removing listeners. ``` -------------------------------- ### FileTransferError Source: https://github.com/ionic-team/capacitor-file-transfer/blob/main/packages/capacitor-plugin/README.md Represents an error that occurred during a file transfer operation, including error codes, messages, and HTTP details. ```APIDOC ## FileTransferError ### Description Details an error that occurred during a file transfer operation. ### Properties #### `code` - **`code`** (string) - A code identifying the specific error (e.g., 'OS-PLUG-FLTR-XXXX'). #### `message` - **`message`** (string) - A human-readable description of the error. #### `source` - **`source`** (string) - The source of the file transfer (URL for download, file path for upload). #### `target` - **`target`** (string) - The target of the file transfer (file path for download, URL for upload). #### `httpStatus` - **`httpStatus`** (number) - The HTTP status code returned by the server, if applicable. #### `headers` - **`headers`** ({ [key: string]: string; }) - The HTTP headers from the server response, if available. #### `body` - **`body`** (string) - The HTTP error response body from the server, if available. #### `exception` - **`exception`** (string) - The exception message thrown on the native side, if available. ### Example ```typescript { code: 'OS-PLUG-FLTR-0010', message: 'The server responded with an HTTP error status code.', source: '/path/to/local/file.txt', target: 'https://example.com/upload', httpStatus: 500, headers: { 'Content-Type': 'application/json' }, body: 'Internal Server Error', exception: 'java.io.IOException: ...' } ``` ``` -------------------------------- ### Remove all registered event listeners from Capacitor File Transfer Source: https://context7.com/ionic-team/capacitor-file-transfer/llms.txt Prevent memory leaks and ensure callbacks are not invoked after a component is destroyed by removing all listeners. This is typically done during component cleanup. ```typescript import { FileTransfer } from '@capacitor/file-transfer'; // Typically called in component lifecycle cleanup async function onPageDestroy() { await FileTransfer.removeAllListeners(); console.log('All FileTransfer listeners removed.'); } ```