Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Cordova Background Upload Plugin

A fast and reliable Cordova plugin for background file uploads that supports any file type. This plugin provides true background upload functionality on iOS and Android, with a browser fallback for web platforms.

Features

  • True Background Uploads - Continues uploading even when app is in background
  • Fast Performance - Optimized for speed with efficient chunked uploads
  • Any File Type - Supports all file types with automatic MIME type detection
  • Progress Tracking - Real-time upload progress with callbacks
  • Retry Logic - Automatic retry with exponential backoff
  • Queue Management - Handle multiple uploads simultaneously
  • Cross-Platform - iOS, Android, and Browser support
  • Cancellation - Cancel uploads at any time
  • Network Optimization - Configurable cellular/WiFi preferences

Installation

Using Cordova CLI

cordova plugin add cordova-plugin-background-upload

Manual Installation

  1. Clone this repository
  2. Add the plugin to your Cordova project:
cordova plugin add /path/to/cordova-plugin-background-upload

Platform Setup

iOS

The plugin automatically configures the necessary background modes and permissions. No additional setup required.

Android

The plugin automatically adds the required permissions to your AndroidManifest.xml. No additional setup required.

Browser

No additional setup required. The plugin provides a fallback implementation using the Fetch API.

Usage

Basic Upload

// Upload a file
BackgroundUpload.upload({
    url: 'https://your-server.com/upload',
    filePath: '/path/to/your/file.jpg',
    fileName: 'photo.jpg',
    mimeType: 'image/jpeg'
})
.then(function(uploadId) {
    console.log('Upload started with ID:', uploadId);
})
.catch(function(error) {
    console.error('Upload failed:', error);
});

Advanced Upload with Options

BackgroundUpload.upload({
    url: 'https://your-server.com/upload',
    filePath: '/path/to/your/video.mp4',
    fileName: 'video.mp4',
    mimeType: 'video/mp4',
    headers: {
        'Authorization': 'Bearer your-token',
        'Custom-Header': 'custom-value'
    },
    parameters: {
        'userId': '12345',
        'category': 'videos',
        'description': 'My video upload'
    },
    method: 'POST',
    allowCellular: true,
    maxRetries: 3,
    timeout: 60
})
.then(function(uploadId) {
    console.log('Upload started:', uploadId);
})
.catch(function(error) {
    console.error('Upload failed:', error);
});

Progress Tracking

// Set up progress callback
BackgroundUpload.onProgress(function(progress) {
    console.log('Upload progress:', progress);
    // progress = {
    //     uploadId: 'upload_123',
    //     status: 'uploading',
    //     progress: 45, // percentage
    //     bytesUploaded: 1024000,
    //     totalBytes: 2048000
    // }
});

// Get progress for specific upload
BackgroundUpload.getProgress('upload_123')
.then(function(progress) {
    console.log('Current progress:', progress);
})
.catch(function(error) {
    console.error('Error getting progress:', error);
});

Completion and Error Handling

// Set up completion callback
BackgroundUpload.onComplete(function(result) {
    console.log('Upload completed:', result);
    // result = {
    //     uploadId: 'upload_123',
    //     status: 'completed',
    //     result: 'Server response data'
    // }
});

// Set up error callback
BackgroundUpload.onError(function(error) {
    console.error('Upload error:', error);
    // error = {
    //     uploadId: 'upload_123',
    //     status: 'failed',
    //     error: 'Network error message'
    // }
});

Upload Management

// Cancel an upload
BackgroundUpload.cancel('upload_123')
.then(function(success) {
    console.log('Upload cancelled:', success);
})
.catch(function(error) {
    console.error('Error cancelling upload:', error);
});

// Get all active uploads
BackgroundUpload.getActiveUploads()
.then(function(uploadIds) {
    console.log('Active uploads:', uploadIds);
})
.catch(function(error) {
    console.error('Error getting active uploads:', error);
});

// Clear completed uploads
BackgroundUpload.clearCompleted()
.then(function(success) {
    console.log('Completed uploads cleared:', success);
})
.catch(function(error) {
    console.error('Error clearing uploads:', error);
});

API Reference

BackgroundUpload.upload(options)

Starts a background upload.

Parameters:

  • options (Object): Upload configuration
    • url (String, required): The upload URL
    • filePath (String, required): Path to the file to upload
    • fileName (String, optional): Name of the file (auto-detected if not provided)
    • mimeType (String, optional): MIME type of the file (auto-detected if not provided)
    • headers (Object, optional): Additional HTTP headers
    • parameters (Object, optional): Additional form parameters
    • method (String, optional): HTTP method (default: 'POST')
    • allowCellular (Boolean, optional): Allow upload over cellular network (default: true)
    • maxRetries (Number, optional): Maximum number of retry attempts (default: 3)
    • timeout (Number, optional): Request timeout in seconds (default: 60)

Returns: Promise that resolves with the upload ID

BackgroundUpload.getProgress(uploadId)

Gets the progress of a specific upload.

Parameters:

  • uploadId (String, required): The upload ID returned from upload()

Returns: Promise that resolves with progress information

BackgroundUpload.cancel(uploadId)

Cancels an active upload.

Parameters:

  • uploadId (String, required): The upload ID to cancel

Returns: Promise that resolves with true if cancelled successfully

BackgroundUpload.getActiveUploads()

Gets all active upload IDs.

Returns: Promise that resolves with array of active upload IDs

BackgroundUpload.clearCompleted()

Clears completed uploads from storage.

Returns: Promise that resolves with true if cleared successfully

BackgroundUpload.onProgress(callback)

Sets the progress callback function.

Parameters:

  • callback (Function): Function to call with progress updates

BackgroundUpload.onComplete(callback)

Sets the completion callback function.

Parameters:

  • callback (Function): Function to call when upload completes

BackgroundUpload.onError(callback)

Sets the error callback function.

Parameters:

  • callback (Function): Function to call when upload fails

Supported File Types

The plugin automatically detects MIME types for common file extensions:

Images

  • JPG, JPEG, PNG, GIF, BMP, WebP, SVG

Videos

  • MP4, AVI, MOV, WMV, FLV, WebM, MKV

Audio

  • MP3, WAV, AAC, OGG, FLAC

Documents

  • PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT, RTF

Archives

  • ZIP, RAR, 7Z, TAR, GZ

Web

  • HTML, HTM, CSS, JS, JSON, XML

For unsupported file types, the plugin defaults to application/octet-stream.

Platform-Specific Notes

iOS

  • Uses NSURLSession background sessions for true background uploads
  • Supports background app refresh and background processing
  • Automatically handles app lifecycle events

Android

  • Uses WorkManager for reliable background processing
  • Runs as a foreground service with notification
  • Handles system kills and restarts gracefully

Browser

  • Uses Fetch API with AbortController for cancellation
  • Limited by browser security restrictions
  • File access requires user interaction

Error Handling

The plugin provides comprehensive error handling:

  • Network connectivity issues
  • File access problems
  • Server errors
  • Timeout errors
  • Cancellation handling

All errors include detailed information about the failure reason.

Performance Tips

  1. Use appropriate chunk sizes - The plugin automatically optimizes chunk sizes for best performance
  2. Configure timeouts - Set appropriate timeout values based on your file sizes and network conditions
  3. Handle retries - The plugin automatically retries failed uploads with exponential backoff
  4. Monitor progress - Use progress callbacks to provide user feedback
  5. Clean up - Clear completed uploads to free up memory

Troubleshooting

Common Issues

  1. Upload not starting

    • Check file path exists and is accessible
    • Verify URL is valid and server is reachable
    • Check network permissions
  2. Upload failing in background

    • Ensure background modes are properly configured (iOS)
    • Check battery optimization settings (Android)
    • Verify foreground service permissions (Android)
  3. Progress not updating

    • Ensure progress callback is set before starting upload
    • Check for JavaScript errors in console
  4. Uploads not completing

    • Check server response format
    • Verify timeout settings
    • Monitor network connectivity

Debug Mode

Enable debug logging by setting the log level in your Cordova configuration:

<preference name="BackgroundUploadLogLevel" value="debug" />

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

For issues and questions:

  1. Check the troubleshooting section above
  2. Search existing issues
  3. Create a new issue with detailed information about your problem

Changelog

Version 1.0.0

  • Initial release
  • Background upload support for iOS and Android
  • Browser fallback implementation
  • Progress tracking and callbacks
  • Retry logic and error handling
  • Comprehensive API documentation

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages