splitMultipart static method

List<String> splitMultipart(
  1. String body,
  2. String boundary
)

Splits a multipart body at its boundary delimiters.

As required by RFC 2046 section 5.1.1 a delimiter is only recognized at the start of a line (or at the very start of the body), so that text merely containing --boundary cannot introduce a part. The CRLF that precedes a delimiter is kept as part of the preceding part's content.

Implementation

static List<String> splitMultipart(String body, String boundary) {
  final delimiter = RegExp(
    '(?:^|\\r\\n)--${RegExp.escape(boundary)}(--)?[ \\t]*(?:\\r\\n|\$)',
  );
  final parts = <String>[];
  int? partStart;
  for (final match in delimiter.allMatches(body)) {
    if (partStart != null) {
      final partEnd = body.startsWith('\r\n', match.start)
          ? match.start + 2
          : match.start;
      parts.add(body.substring(partStart, partEnd));
    }
    if (match.group(1) != null) {
      // closing delimiter, anything after it is the epilogue
      return parts;
    }
    partStart = match.end;
  }
  if (partStart != null) {
    // no closing delimiter: the remainder is the last part
    parts.add(body.substring(partStart));
  }

  return parts;
}