parse static method

HttpMultipartFormData parse(
  1. MimeMultipart multipart, {
  2. Encoding defaultEncoding = utf8,
})

Parse a MimeMultipart and return a HttpMultipartFormData.

If the Content-Disposition header is missing or invalid, an HttpException is thrown.

If the MimeMultipart is identified as text, and the Content-Type header is missing, the data is decoded using defaultEncoding. See more information in the HTML5 spec(http://dev.w3.org/html5/spec-preview/ constraints.html#multipart-form-data).

Implementation

static HttpMultipartFormData parse(MimeMultipart multipart,
    {Encoding defaultEncoding = utf8}) {
  ContentType? contentType;
  HeaderValue? encoding;
  HeaderValue? disposition;
  for (var key in multipart.headers.keys) {
    switch (key) {
      case 'content-type':
        contentType = ContentType.parse(multipart.headers[key]!);
        break;

      case 'content-transfer-encoding':
        encoding = HeaderValue.parse(multipart.headers[key]!);
        break;

      case 'content-disposition':
        disposition = HeaderValue.parse(multipart.headers[key]!,
            preserveBackslash: true);
        break;

      default:
        break;
    }
  }
  if (disposition == null) {
    throw const HttpException(
        "Mime Multipart doesn't contain a Content-Disposition header value");
  }
  if (encoding != null &&
      !_transparentEncodings.contains(encoding.value.toLowerCase())) {
    // TODO(ajohnsen): Support BASE64, etc.
    throw HttpException('Unsupported contentTransferEncoding: '
        '${encoding.value}');
  }

  Stream stream = multipart;
  var isText = contentType == null ||
      contentType.primaryType == 'text' ||
      contentType.mimeType == 'application/json';
  if (isText) {
    Encoding? encoding;
    if (contentType?.charset != null) {
      encoding = Encoding.getByName(contentType!.charset);
    }
    encoding ??= defaultEncoding;
    stream = stream.transform(encoding.decoder);
  }
  return HttpMultipartFormData._(
      contentType, disposition, encoding, multipart, stream, isText);
}