multiPart abstract method

Future<Response> multiPart(
  1. String endpoint, {
  2. String method = 'POST',
  3. Map<String, String>? fields,
  4. Map<String, PFile<Object>>? files,
  5. Duration? timeLimit,
  6. ResponseTimeoutCallback? onTimeout,
  7. @visibleForTesting Client? testClient,
})

A shortcut to send with MultipartRequest. This is usually for uploading fields with files and/or images.

  • method defaults to POST.

  • fields when using http's Client, this is basically the same as

    final postUri = Uri.parse('http://your-api.com/your_endpoint');
    final request = http.MultipartRequest('POST', postUri)
      ..fields['field1'] = field1
      ..fields['field2'] = field2;
    
    final streamedResponse = await request.send();
    final response = await Response.fromStream(streamedResponse);
    

    but in a more elegant way, for example:

    final postor = Postor('my-api.com');
    final fields = {
      'field1': field1,
      'field2': field2,
    };
    final response = await postor.multiPart(
      '/my_endpoint',
      fields: fields,
    );
    

    note that we don't need to specify the POST method as it's already the default value.

  • files specify the field name and both file path/file bytes and file name (optional) using PFile here, for example:

    final postor = Postor('my-api.com');
    final files = {
      'photo': PFileFromPath(photo_path),
      // if using bytes
      // 'photo': PFileFromBytes(photo_bytes)
      'photo_small': PFileFromPath(photo_small_path, filename: 'photo_small.png'),
    };
    final response = await postor.multiPart(
      '/upload_photos',
      files: files,
    );
    

    note: by default Postor will handle these files in an isolate, so theoritically there should not be any UI blocking problem.

  • timeLimit an optional different timeout if needed

  • onTimeout an optional callback when timeLimit has exceeded

final notes:

  • both files/images processing and request can be cancelled via cancel or via CTManager.cancel. for example:
// our target url is https://my-api.com/upload
final postor = Postor('https://my-api.com');
final files = {
  'photo': PFileFromPath(photo_path, filename: 'photo.jpg'),
  'photo_small': PFileFromPath(photo_small_path),
};

postor.multiPart(
    '/upload',
    files: files,
).then((response) => print(response.body));

// lets cancel it after 1 second
postor.cancel('https://my-api.com/upload');

for more info about CTManager: https://pub.dev/documentation/ctmanager/latest/

Implementation

Future<Response> multiPart(
  String endpoint, {
  String method = 'POST',
  Map<String, String>? fields,
  Map<String, PFile>? files,
  Duration? timeLimit,
  ResponseTimeoutCallback? onTimeout,
  @visibleForTesting Client? testClient,
});