toListFormData method

Future<List> toListFormData()

Implementation

Future<List<dynamic>> toListFormData() async {
  final List<dynamic> formDataList = [];
  if (boundary.isNotEmpty) {
    final separator = '--$boundary\r\n';
    final close = '--$boundary--\r\n';
    final data = utf8.decode(await bodyBytes.toBytes(), allowMalformed: true);
    final clearData = data.replaceAll(close, '');
    final inputList = clearData.split(separator).toList();

    for (final String inputString in inputList) {
      if (inputString.contains('content-disposition: form-data')) {
        if (inputString.contains('filename')) {
          final List<String> parts =
              inputString.split('\r\n').where((e) => e.isNotEmpty).toList();
          if (parts.length >= 2) {
            final String stringContainFileName = parts[0];
            final String stringContainContentType = parts[1];
            final String content = parts[2];
            String fileName = '';
            String contentType = '';

            final RegExp regexFn = RegExp('filename="([^"]+)"');
            final Match? matchFn = regexFn.firstMatch(stringContainFileName);
            if (matchFn != null) {
              fileName = matchFn.group(1)!;
            }

            final RegExp regexCt = RegExp('content-type: ([^ ]+)');
            final Match? matchCt =
                regexCt.firstMatch(stringContainContentType);
            if (matchCt != null) {
              contentType = matchCt.group(1)!;
            }

            if (fileName.isNotEmpty && contentType.isNotEmpty) {
              formDataList.add(
                AliceFormDataFile(fileName, contentType, content.length),
              );
            }
          }
        } else if (inputString.contains('name')) {
          final List<String> parts =
              inputString.split('\r\n').where((e) => e.isNotEmpty).toList();
          if (parts.length >= 2) {
            final String stringContainName = parts[0];
            final String value = parts[1];
            String name = '';

            final RegExp regex = RegExp('name="([^"]+)"');
            final Match? match = regex.firstMatch(stringContainName);
            if (match != null) {
              name = match.group(1)!;
            }

            if (name.isNotEmpty && value.isNotEmpty) {
              formDataList.add(AliceFormDataField(name, value));
            }
          }
        }
      }
    }
  }
  return formDataList;
}