快速入门
-
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
Add background modes to your
Info.plist:<key>UIBackgroundModes</key><array><string>processing</string></array>Android
Section titled “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" />
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);};
// Listen for upload eventsconst listener = await Uploader.addListener('events', (event) => { switch (event.name) { case 'uploading': console.log(`Upload ${event.payload.id}: ${event.payload.percent}%`); break; case 'completed': console.log('Upload completed:', event.payload.id); console.log('Status code:', event.payload.statusCode); break; case 'failed': console.error('Upload failed:', event.payload.id); console.error('Error:', event.payload.error); break; }});
// Remember to remove listener when done// listener.remove();
// 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
Section titled “API Reference”startUpload(options)
Section titled “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)
Section titled “cancelUpload(options)”Cancels an ongoing upload.
interface CancelOptions { id: string;}getUploads()
Section titled “getUploads()”Returns all active uploads.
removeUpload(options)
Section titled “removeUpload(options)”Removes an upload from the queue.
interface RemoveOptions { id: string;}Events
Section titled “Events”events
Section titled “events”All upload events are delivered through a single events listener. The event contains a name field to identify the type:
Uploader.addListener('events', (event: UploadEvent) => { switch (event.name) { case 'uploading': // Upload in progress console.log(`Progress: ${event.payload.percent}%`); console.log(`ID: ${event.payload.id}`); break;
case 'completed': // Upload finished successfully console.log(`Completed: ${event.payload.id}`); console.log(`Status code: ${event.payload.statusCode}`); break;
case 'failed': // Upload failed console.error(`Failed: ${event.payload.id}`); console.error(`Error: ${event.payload.error}`); break; }});Event Types:
uploading- Progress update withpercentandidcompleted- Upload finished withidandstatusCodefailed- Upload failed withidanderrormessage
Advanced Features
Section titled “Advanced Features”Multipart Form Upload
Section titled “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
Section titled “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
Section titled “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
Section titled “Best Practices”-
Handle all event types
const setupUploadHandlers = () => {Uploader.addListener('events', (event) => {switch (event.name) {case 'uploading':handleProgress(event.payload);break;case 'completed':handleCompleted(event.payload);break;case 'failed':handleError(event.payload);break;}});}; -
Clean up listeners
// Add listenerconst listener = await Uploader.addListener('events', handleEvent);// Clean up when donelistener.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
Section titled “Platform Notes”- Uses
URLSessionfor background uploads - Requires background processing capability
- Uploads continue when app is suspended
Android
Section titled “Android”- Uses
WorkManagerfor reliable uploads - Shows foreground service notification during uploads
- Respects battery optimization settings