getHeaderFormData method

Future<Map> getHeaderFormData()

Retrieves form data from a multipart/form-data request.

This method processes the multipart form data, extracting fields and files from the request. Fields are stored as a map of strings, while files are stored as a map of byte lists.

Returns a Future<Map<String, dynamic>> containing:

  • fields: A map of form fields with their respective values.
  • files: A map of files with their contents as byte lists.

Implementation

Future<Map> getHeaderFormData() async {
  final fields = <String, String>{};
  final files = <String, List<int>>{};

  /// Parse the multipart form data. beacuse some time the requested multipart/form-data is empty
  try {
    final contentType = _rq.headers.contentType;
    if (contentType?.mimeType == 'multipart/form-data') {
      final transformer =
          MimeMultipartTransformer(contentType!.parameters['boundary']!);

      final parts = await transformer.bind(_rq).toList();

      await Future.forEach(parts, (part) async {
        final contentDisposition = part.headers['content-disposition'];
        if (contentDisposition != null) {
          final nameMatch =
              RegExp(r'name="(.+?)"').firstMatch(contentDisposition);
          final filenameMatch =
              RegExp(r'filename="(.+?)"').firstMatch(contentDisposition);
          if (filenameMatch != null) {
            //final filename = filenameMatch.group(1);
            final fileBytes = await part
                .fold<List<int>>([], (bytes, data) => bytes..addAll(data));
            files[nameMatch!.group(1)!] = fileBytes;
          } else {
            final value = await utf8.decodeStream(part);
            fields[nameMatch!.group(1)!] = value;
          }
        }
      });
    }
  } catch (e) {
    Console.w(e);
  }

  return {
    'fields': fields,
    'files': files,
  };
}