postMultipart method

Future<TestResponse> postMultipart(
  1. String path, {
  2. Map<String, String>? fields,
  3. Map<String, MultipartFileData>? files,
  4. Map<String, String>? headers,
})

Sends a POST request with multipart/form-data body.

Example:

final res = await client.postMultipart('/upload',
  fields: {'name': 'John'},
  files: {
    'avatar': MultipartFileData(
      filename: 'photo.png',
      bytes: imageBytes,
      contentType: 'image/png',
    ),
  },
);

Implementation

Future<TestResponse> postMultipart(
  String path, {
  Map<String, String>? fields,
  Map<String, MultipartFileData>? files,
  Map<String, String>? headers,
}) async {
  final boundary =
      'chase-test-boundary-${DateTime.now().millisecondsSinceEpoch}';
  final body = _buildMultipartBody(boundary, fields ?? {}, files ?? {});

  final effectiveHeaders = Map<String, String>.from(headers ?? {});
  effectiveHeaders['content-type'] =
      'multipart/form-data; boundary=$boundary';

  final uri = Uri.parse('http://localhost:$_port$path');
  final req = await _client.openUrl('POST', uri);
  req.followRedirects = false;

  effectiveHeaders.forEach((key, value) {
    req.headers.set(key, value);
  });

  req.add(body);
  final res = await req.close();
  return TestResponse(res);
}