Getting Started
-
Install the package
Terminal window npm i @capgo/capacitor-uploaderTerminal window pnpm add @capgo/capacitor-uploaderTerminal window yarn add @capgo/capacitor-uploaderTerminal window bun add @capgo/capacitor-uploader -
Sync with native projects
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync -
Configure permissions
iOS
Add background modes to your
Info.plist
:<key>UIBackgroundModes</key><array><string>processing</string></array>Android
Add permissions to your
AndroidManifest.xml
:<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Usage
Import the plugin and use its methods to upload files:
import { Uploader } from '@capgo/capacitor-uploader';
// Start an uploadconst startUpload = async () => { const upload = await Uploader.startUpload({ filePath: 'file:///path/to/your/file.jpg', serverUrl: 'https://your-server.com/upload', method: 'POST', headers: { 'Authorization': 'Bearer your-token' }, parameters: { 'userId': '12345', 'type': 'profile' }, notificationTitle: 'Uploading Photo' });
console.log('Upload ID:', upload.id);};
// Monitor upload progressconst monitorProgress = async (uploadId: string) => { const listener = await Uploader.addListener( 'progressEvent', (progress) => { if (progress.id === uploadId) { console.log(`Progress: ${progress.progress}%`); console.log(`Bytes sent: ${progress.bytesSent}/${progress.bytesTotal}`); } } );
// Remember to remove listener when done // listener.remove();};
// Handle upload completionconst handleCompletion = async () => { const listener = await Uploader.addListener( 'completedEvent', (result) => { console.log('Upload completed:', result.id); console.log('Server response:', result.response); } );};
// Handle upload errorsconst handleErrors = async () => { const listener = await Uploader.addListener( 'errorEvent', (error) => { console.error('Upload failed:', error.id); console.error('Error:', error.error); } );};
// Cancel an uploadconst cancelUpload = async (uploadId: string) => { await Uploader.cancelUpload({ id: uploadId });};
// Get all active uploadsconst getActiveUploads = async () => { const uploads = await Uploader.getUploads(); console.log('Active uploads:', uploads);};
API Reference
startUpload(options)
Starts a new file upload.
interface UploadOptions { filePath: string; serverUrl: string; method?: 'POST' | 'PUT'; headers?: { [key: string]: string }; parameters?: { [key: string]: string }; notificationTitle?: string; notificationBody?: string; useUtf8Charset?: boolean; maxRetries?: number;}
cancelUpload(options)
Cancels an ongoing upload.
interface CancelOptions { id: string;}
getUploads()
Returns all active uploads.
removeUpload(options)
Removes an upload from the queue.
interface RemoveOptions { id: string;}
Events
progressEvent
Fired during upload progress.
interface ProgressEvent { id: string; progress: number; // 0-100 bytesSent: number; bytesTotal: number;}
completedEvent
Fired when upload completes successfully.
interface CompletedEvent { id: string; response: string; statusCode: number;}
errorEvent
Fired when upload fails.
interface ErrorEvent { id: string; error: string; statusCode?: number;}
Advanced Features
Multipart Form Upload
const uploadWithFormData = async () => { const upload = await Uploader.startUpload({ filePath: 'file:///path/to/photo.jpg', serverUrl: 'https://api.example.com/upload', method: 'POST', parameters: { 'name': 'profile-photo', 'description': 'User profile photo' }, headers: { 'X-API-Key': 'your-api-key' } });};
Binary Upload
const uploadBinary = async () => { const upload = await Uploader.startUpload({ filePath: 'file:///path/to/data.bin', serverUrl: 'https://api.example.com/binary', method: 'PUT', headers: { 'Content-Type': 'application/octet-stream' } });};
Network-Aware Uploading
import { Network } from '@capacitor/network';
const smartUpload = async () => { const status = await Network.getStatus();
if (status.connectionType === 'wifi') { // Start large file uploads on WiFi await startLargeUpload(); } else if (status.connectionType === 'cellular') { // Queue for later or warn user console.log('Using cellular data'); }};
Best Practices
-
Handle all events
const setupUploadHandlers = () => {Uploader.addListener('progressEvent', handleProgress);Uploader.addListener('completedEvent', handleCompleted);Uploader.addListener('errorEvent', handleError);}; -
Clean up listeners
const listeners: PluginListenerHandle[] = [];// Add listenerslisteners.push(await Uploader.addListener(...));// Clean up when donelisteners.forEach(listener => listener.remove()); -
Retry failed uploads
const retryUpload = async (filePath: string, serverUrl: string) => {try {await Uploader.startUpload({filePath,serverUrl,maxRetries: 3});} catch (error) {console.error('Upload failed after retries:', error);}}; -
Show upload notifications
await Uploader.startUpload({filePath: 'file:///path/to/file',serverUrl: 'https://server.com/upload',notificationTitle: 'Uploading File',notificationBody: 'Your file is being uploaded...'});
Platform Notes
iOS
- Uses
URLSession
for background uploads - Requires background processing capability
- Uploads continue when app is suspended
Android
- Uses
WorkManager
for reliable uploads - Shows foreground service notification during uploads
- Respects battery optimization settings