Skip to content

LaithMahdi/upload-image-flutter-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Flutter Image Upload Demo

A comprehensive Flutter application demonstrating image upload functionality with multiple methods and UI options.

πŸ“± Features

  • Multiple Image Selection - Camera, Gallery, and Multiple images
  • Various Upload Methods - Single, Multiple, and Base64 uploads
  • Progress Tracking - Real-time upload progress with visual indicators
  • Different UI Screens - Multiple demo screens showcasing different approaches
  • Error Handling - Comprehensive error handling and user feedback
  • Free Testing - Uses httpbin.org for free API testing

πŸš€ Screenshots

The app includes several demo screens:

  • Main navigation screen
  • Simple image upload
  • Enhanced upload with progress
  • Multiple upload options

πŸ›  Installation

Prerequisites

  • Flutter SDK (3.0 or higher)
  • Dart SDK
  • Android Studio / VS Code
  • Android device or emulator

Setup

  1. Clone the repository

    git clone <your-repo-url>
    cd tessssts
  2. Install dependencies

    flutter pub get
  3. Run the app

    flutter run

πŸ“¦ Dependencies

The app uses the following key packages:

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.8
  dio: ^5.4.0 # HTTP client for uploads
  image_picker: ^1.0.7 # Image selection from camera/gallery
  path: ^1.8.3 # Path manipulation utilities
  path_provider: ^2.1.2 # Platform-specific directories

πŸ— Architecture

Core Components

  1. Services

    • ImageUploadService - Handles all upload operations
    • ApiClient - Simplified API interface
  2. Screens

    • main.dart - Navigation and main screen
    • ImageUploadScreen - Full-featured upload demo
    • EnhancedImageUploadScreen - Advanced upload options
    • SimpleUploadDemo - Basic upload example

Upload Methods

1. Single Image Upload

final response = await ImageUploadService.uploadImage(
  url: 'https://httpbin.org/post',
  imageFile: selectedImage,
  fieldName: 'file',
  onSendProgress: (sent, total) {
    // Update progress
  },
);

2. Multiple Images Upload

final response = await ImageUploadService.uploadMultipleImages(
  url: 'https://httpbin.org/post',
  imageFiles: selectedImages,
  fieldName: 'file',
  onSendProgress: (sent, total) {
    // Update progress
  },
);

3. Base64 Upload

final response = await ImageUploadService.uploadImageAsBase64(
  url: 'https://httpbin.org/post',
  imageFile: selectedImage,
  fieldName: 'file',
  headers: {'Content-Type': 'application/json'},
);

🌐 API Configuration

The app currently uses httpbin.org for testing:

  • Base URL: https://httpbin.org
  • Endpoint: /post
  • Method: POST
  • Content-Type: multipart/form-data or application/json
  • Field Name: file
  • Authentication: Not required

Switching to Production API

To use your own API, update the configuration in your upload methods:

// In your upload calls, change:
url: 'https://httpbin.org/post'
// To:
url: 'https://your-api.com/upload'

// And add authentication if needed:
headers: {
  'Authorization': 'Bearer your-token',
  'Content-Type': 'multipart/form-data',
}

πŸ“ Usage Examples

Basic Image Upload

// Pick an image
final XFile? image = await ImageUploadService.pickImage(
  source: ImageSource.gallery,
);

// Upload the image
if (image != null) {
  final response = await ImageUploadService.uploadImage(
    url: 'https://httpbin.org/post',
    imageFile: image,
    fieldName: 'file',
  );

  if (response?.statusCode == 200) {
    print('Upload successful!');
  }
}

Upload with Progress Tracking

await ImageUploadService.uploadImage(
  url: 'https://httpbin.org/post',
  imageFile: selectedImage,
  fieldName: 'file',
  onSendProgress: (int sent, int total) {
    double progress = sent / total;
    print('Upload progress: ${(progress * 100).toStringAsFixed(1)}%');
  },
);

🎨 UI Components

Image Selection Options

  • Camera: Take a photo directly
  • Gallery: Select from device gallery
  • Multiple: Select multiple images at once

Progress Indicators

  • Linear progress bar during upload
  • Percentage display
  • Status messages

Error Handling

  • Network error messages
  • File size validation
  • Format validation
  • Retry mechanisms

πŸ”§ Customization

Changing Upload Configuration

Edit lib/services/image_upload_service.dart:

// Configure Dio settings
ImageUploadService.configureDio(
  baseUrl: 'https://your-api.com',
  connectTimeout: const Duration(seconds: 30),
  receiveTimeout: const Duration(seconds: 30),
  sendTimeout: const Duration(minutes: 5),
);

Adding New Upload Methods

static Future<Response?> customUpload({
  required String url,
  required XFile imageFile,
  Map<String, String>? customHeaders,
}) async {
  // Your custom upload logic
}

πŸ“± Platform Support

  • βœ… Android - Fully supported
  • βœ… iOS - Fully supported
  • ⚠️ Web - Limited (file picker restrictions)
  • ⚠️ Desktop - Limited (file picker restrictions)

πŸ› Troubleshooting

Common Issues

  1. "Unexpected field" error

    • Check field name matches API expectations
    • Verify Content-Type header
  2. Upload timeout

    • Increase timeout settings in Dio configuration
    • Check network connection
  3. Permission denied

    • Ensure camera/storage permissions in android/app/src/main/AndroidManifest.xml

Debug Mode

Enable detailed logging by setting:

// In image_upload_service.dart
print('Upload progress: ${(sent / total * 100).toStringAsFixed(1)}%');
print('Response: ${response.data}');

πŸ“„ License

This project is open source and available under the MIT License.

🀝 Contributing

  1. Fork the project
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“ž Support

If you have any questions or issues:

  • Create an issue in the repository
  • Check the troubleshooting section
  • Review the Flutter documentation

πŸ”„ Version History

  • v1.0.0 - Initial release with basic upload functionality
  • v1.1.0 - Added multiple upload methods and progress tracking
  • v1.2.0 - Enhanced UI and error handling
  • v1.3.0 - Switched to httpbin.org for free testing

Made with ❀️ using Flutter

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published