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.
- ✅ 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
cordova plugin add cordova-plugin-background-upload- Clone this repository
- Add the plugin to your Cordova project:
cordova plugin add /path/to/cordova-plugin-background-uploadThe plugin automatically configures the necessary background modes and permissions. No additional setup required.
The plugin automatically adds the required permissions to your AndroidManifest.xml. No additional setup required.
No additional setup required. The plugin provides a fallback implementation using the Fetch API.
// 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);
});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);
});// 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);
});// 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'
// }
});// 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);
});Starts a background upload.
Parameters:
options(Object): Upload configurationurl(String, required): The upload URLfilePath(String, required): Path to the file to uploadfileName(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 headersparameters(Object, optional): Additional form parametersmethod(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
Gets the progress of a specific upload.
Parameters:
uploadId(String, required): The upload ID returned from upload()
Returns: Promise that resolves with progress information
Cancels an active upload.
Parameters:
uploadId(String, required): The upload ID to cancel
Returns: Promise that resolves with true if cancelled successfully
Gets all active upload IDs.
Returns: Promise that resolves with array of active upload IDs
Clears completed uploads from storage.
Returns: Promise that resolves with true if cleared successfully
Sets the progress callback function.
Parameters:
callback(Function): Function to call with progress updates
Sets the completion callback function.
Parameters:
callback(Function): Function to call when upload completes
Sets the error callback function.
Parameters:
callback(Function): Function to call when upload fails
The plugin automatically detects MIME types for common file extensions:
- JPG, JPEG, PNG, GIF, BMP, WebP, SVG
- MP4, AVI, MOV, WMV, FLV, WebM, MKV
- MP3, WAV, AAC, OGG, FLAC
- PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT, RTF
- ZIP, RAR, 7Z, TAR, GZ
- HTML, HTM, CSS, JS, JSON, XML
For unsupported file types, the plugin defaults to application/octet-stream.
- Uses
NSURLSessionbackground sessions for true background uploads - Supports background app refresh and background processing
- Automatically handles app lifecycle events
- Uses
WorkManagerfor reliable background processing - Runs as a foreground service with notification
- Handles system kills and restarts gracefully
- Uses Fetch API with AbortController for cancellation
- Limited by browser security restrictions
- File access requires user interaction
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.
- Use appropriate chunk sizes - The plugin automatically optimizes chunk sizes for best performance
- Configure timeouts - Set appropriate timeout values based on your file sizes and network conditions
- Handle retries - The plugin automatically retries failed uploads with exponential backoff
- Monitor progress - Use progress callbacks to provide user feedback
- Clean up - Clear completed uploads to free up memory
-
Upload not starting
- Check file path exists and is accessible
- Verify URL is valid and server is reachable
- Check network permissions
-
Upload failing in background
- Ensure background modes are properly configured (iOS)
- Check battery optimization settings (Android)
- Verify foreground service permissions (Android)
-
Progress not updating
- Ensure progress callback is set before starting upload
- Check for JavaScript errors in console
-
Uploads not completing
- Check server response format
- Verify timeout settings
- Monitor network connectivity
Enable debug logging by setting the log level in your Cordova configuration:
<preference name="BackgroundUploadLogLevel" value="debug" />MIT License - see LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
For issues and questions:
- Check the troubleshooting section above
- Search existing issues
- Create a new issue with detailed information about your problem
- Initial release
- Background upload support for iOS and Android
- Browser fallback implementation
- Progress tracking and callbacks
- Retry logic and error handling
- Comprehensive API documentation