multipartkit

Parse, query and build multipart bodies such as multipart/form-data uploads, on Erlang and JavaScript.

For bodies too large to hold in memory, see multipartkit/stream.

Types

A parsed Content-Disposition header value.

pub type ContentDisposition {
  ContentDisposition(
    disposition: String,
    name: option.Option(String),
    filename: option.Option(String),
    parameters: List(#(String, String)),
  )
}

Constructors

  • ContentDisposition(
      disposition: String,
      name: option.Option(String),
      filename: option.Option(String),
      parameters: List(#(String, String)),
    )

    Arguments

    disposition

    The disposition type in lowercase, such as "form-data" or "attachment".

    name

    The name parameter.

    filename

    The filename* parameter decoded from RFC 5987 form when present, otherwise the filename parameter.

    parameters

    Every parameter in input order, with quoted strings unquoted and * forms not decoded.

Upper bounds that parse and stream.parse enforce while reading.

A value equal to a limit is allowed. Start from default_limits and change the fields you need:

multipartkit.Limits(..multipartkit.default_limits, max_parts: 10)
pub type Limits {
  Limits(
    max_body_bytes: Int,
    max_part_bytes: Int,
    max_parts: Int,
    max_header_bytes: Int,
  )
}

Constructors

  • Limits(
      max_body_bytes: Int,
      max_part_bytes: Int,
      max_parts: Int,
      max_header_bytes: Int,
    )

    Arguments

    max_body_bytes

    Bytes in the whole body, including the preamble and epilogue.

    max_part_bytes

    Bytes in one part body.

    max_parts

    Number of parts.

    max_header_bytes

    Bytes in one part’s header block.

Why a multipart body could not be parsed, built or queried.

Variants that hold a String hold the offending input.

pub type MultipartError {
  MissingBoundary
  InvalidContentType(content_type: String)
  InvalidBoundary(boundary: String)
  UnsupportedMediaType(media_type: String)
  InvalidHeader(line: String)
  InvalidContentDisposition(value: String)
  InvalidQuotedPair(value: String)
  UnexpectedEndOfInput
  BodyTooLarge(limit: Int)
  PartTooLarge(limit: Int)
  TooManyParts(limit: Int)
  HeaderTooLarge(limit: Int)
  InvalidHeaderName(name: String)
  InvalidHeaderValue(name: String, value: String)
  EmptyFieldName(name: String)
  MissingField(name: String)
  InvalidUtf8Field(name: String)
  MissingFile(name: String)
  DisallowedContentType(content_type: String)
}

Constructors

  • MissingBoundary

    The Content-Type has no boundary parameter.

  • InvalidContentType(content_type: String)

    The Content-Type is not a media type with parameters, or has a parameter more than once.

  • InvalidBoundary(boundary: String)

    The boundary is empty, longer than 70 characters, ends in a space or contains a character RFC 2046 does not allow, or a line of a part given to encode or stream.encode starts with -- and the boundary.

  • UnsupportedMediaType(media_type: String)

    The media type is not multipart/*.

  • InvalidHeader(line: String)

    A header line has no :, has a name that is empty or holds a space, tab or other character outside printable ASCII, holds CR or NUL, or is a continuation line with no header before it. It holds the line, or "" when the header block is not UTF-8.

  • InvalidContentDisposition(value: String)

    A Content-Disposition value could not be parsed or has a parameter more than once. It holds the value.

  • InvalidQuotedPair(value: String)

    A Content-Disposition quoted string escapes a control character, as in \ followed by NUL. It holds the value.

  • UnexpectedEndOfInput

    The body ended before the closing boundary.

  • BodyTooLarge(limit: Int)

    The body is larger than Limits.max_body_bytes.

  • PartTooLarge(limit: Int)

    A part body is larger than Limits.max_part_bytes.

  • TooManyParts(limit: Int)

    The body has more parts than Limits.max_parts.

  • HeaderTooLarge(limit: Int)

    A part’s header block is larger than Limits.max_header_bytes.

  • InvalidHeaderName(name: String)

    A header name given to new_part is empty or holds :, a space, a tab or another character outside printable ASCII.

  • InvalidHeaderValue(name: String, value: String)

    A header value given to new_part, or a name, filename or content type given to new_field or new_file, contains CR, LF or NUL.

  • EmptyFieldName(name: String)

    The field name given to new_field or new_file is empty or only whitespace.

  • MissingField(name: String)

    field found no text field with this name.

  • InvalidUtf8Field(name: String)

    field found the text field, but its body is not UTF-8.

  • MissingFile(name: String)

    file found no file part with this name.

  • DisallowedContentType(content_type: String)

    allowed_content_types rejected the part’s Content-Type. It holds the Content-Type, or "" when the part has none.

One part of a multipart body: its headers and its body bytes.

Get one from parse, new_field, new_file or new_part. The name, filename and content_type functions read values taken from the headers.

pub opaque type Part

Values

pub fn allowed_content_types(
  part: Part,
  allowed: List(String),
) -> Result(Part, MultipartError)

Returns the part when its media type is one of allowed, ignoring ASCII case and parameters such as charset.

Returns Error(DisallowedContentType(content_type)) otherwise. A part with no Content-Type is checked as "". The Content-Type is what the client sent, so check the bytes too when it matters.

Examples

allowed_content_types(avatar, ["image/png", "image/jpeg"])
// -> Ok(avatar)
pub fn body(part: Part) -> BitArray

Returns the part’s body bytes.

pub fn content_type(part: Part) -> option.Option(String)

Returns the value of the part’s Content-Type header.

pub const default_limits: Limits

10 MB body, 5 MB per part, 100 parts and 16 KiB of headers per part.

pub fn encode(
  parts: List(Part),
  boundary: String,
) -> Result(BitArray, MultipartError)

Encodes parts with the given boundary.

Returns Error(InvalidBoundary(boundary)) when the boundary is empty, longer than 70 characters, ends in a space or contains a character RFC 2046 does not allow, or when a header or body line of a part starts with -- and the boundary, which a receiver would read as a delimiter. Use encode_form to get a random boundary instead.

Examples

let assert Ok(title) = new_field(name: "title", value: "hi")
encode([title], "b")
// -> Ok(<<
//   "--b\r\n",
//   "Content-Disposition: form-data; name=\"title\"\r\n\r\n",
//   "hi\r\n",
//   "--b--\r\n",
// >>)
encode([], "")
// -> Error(InvalidBoundary(""))
pub fn encode_form(parts: List(Part)) -> #(String, BitArray)

Encodes parts as multipart/form-data with a new random boundary and returns #(content_type, body), where content_type is the value for the HTTP Content-Type header.

The boundary comes from int.random, which is not cryptographically strong. A boundary that a line of a part starts with is drawn again.

Examples

let assert Ok(title) = new_field(name: "title", value: "hi")
let #(content_type, body) = encode_form([title])
// content_type -> "multipart/form-data; boundary=----multipartkit-..."
pub fn field(
  parts: List(Part),
  name: String,
) -> Result(String, MultipartError)

Returns the first text field with this name, decoded as UTF-8. A text field is a form-data part with a name and no filename.

Returns Error(MissingField(name)) when there is none, and Error(InvalidUtf8Field(name)) when its body is not UTF-8.

Examples

field(parts, "title")
// -> Ok("hello")
field(parts, "missing")
// -> Error(MissingField("missing"))
pub fn fields(parts: List(Part), name: String) -> List(String)

Returns every text field with this name in input order, skipping bodies that are not UTF-8.

pub fn file(
  parts: List(Part),
  name: String,
) -> Result(Part, MultipartError)

Returns the first file part with this name. A file part is a form-data part with a filename, even an empty one, which is what browsers send for a file input left empty.

Returns Error(MissingFile(name)) when there is none.

pub fn filename(part: Part) -> option.Option(String)

Returns the filename of a form-data part, preferring the RFC 5987 filename* parameter.

The filename is exactly what the client sent and may contain ../ or an absolute path. Do not join it onto a server path unchecked.

pub fn files(parts: List(Part), name: String) -> List(Part)

Returns every file part with this name in input order.

pub fn header(part: Part, name: String) -> Result(String, Nil)

Returns the value of the first header whose name matches, ignoring ASCII case.

Examples

header(part, "content-type")
// -> Ok("image/png")
header(part, "x-missing")
// -> Error(Nil)
pub fn headers(part: Part) -> List(#(String, String))

Returns every header of the part in the order it was written, with the names as written.

pub fn infer_content_type(
  filename: String,
  body: BitArray,
) -> String

Guesses a content type from the filename’s extension, then from the body’s leading bytes, using nao1215/mimetype. Returns "application/octet-stream" when neither is recognised.

Plain printable text with no known extension is "text/plain".

Examples

infer_content_type("photo.png", <<>>)
// -> "image/png"
infer_content_type("blob", <<0x89, "PNG":utf8, 0x0D, 0x0A, 0x1A, 0x0A>>)
// -> "image/png"
infer_content_type("blob", <<0, 1, 2>>)
// -> "application/octet-stream"
pub fn name(part: Part) -> option.Option(String)

Returns the name parameter of a form-data part’s Content-Disposition. Other parts have no name.

pub fn names(parts: List(Part)) -> List(String)

Returns the field names in the order they first appear, without duplicates.

pub fn new_field(
  name name: String,
  value value: String,
) -> Result(Part, MultipartError)

Creates a text field part for a multipart/form-data body.

Returns Error(InvalidHeaderValue(..)) when the name contains CR, LF or NUL, and otherwise Error(EmptyFieldName(name)) when it is empty or only whitespace.

Examples

let assert Ok(title) = new_field(name: "title", value: "hello")
name(title)
// -> Some("title")
new_field(name: "", value: "hello")
// -> Error(EmptyFieldName(""))
pub fn new_file(
  name name: String,
  filename filename: String,
  content_type content_type: String,
  body body: BitArray,
) -> Result(Part, MultipartError)

Creates a file part for a multipart/form-data body.

The filename is written as UTF-8 in the quoted filename parameter, as browsers do. RFC 7578 §4.2 forbids the RFC 5987 filename* form here. The errors are the same as new_field, and the filename and content type are checked for CR, LF and NUL too. infer_content_type can pick the content type.

Examples

let assert Ok(avatar) =
  new_file(
    name: "avatar",
    filename: "cat.png",
    content_type: "image/png",
    body: png_bytes,
  )
filename(avatar)
// -> Some("cat.png")
pub fn new_part(
  headers headers: List(#(String, String)),
  body body: BitArray,
) -> Result(Part, MultipartError)

Creates a part from raw headers, for bodies such as multipart/mixed.

Header values lose leading and trailing spaces and tabs, as parse does. name, filename and content_type are read from the headers in the same way as for a parsed part.

Returns Error(InvalidHeaderName(name)) for a header name that is empty or holds :, a space, a tab or another character outside printable ASCII, as parse would reject it. Returns Error(InvalidHeaderValue(name, value)) for a value with CR, LF or NUL, and Error(InvalidContentDisposition(value)) or Error(InvalidQuotedPair(value)) when the Content-Disposition header cannot be parsed.

Examples

let assert Ok(part) =
  new_part(headers: [#("Content-Type", "text/plain")], body: <<"hi">>)
content_type(part)
// -> Some("text/plain")
new_part(headers: [#("X-Note", "a\r\nb")], body: <<>>)
// -> Error(InvalidHeaderValue("X-Note", "a\r\nb"))
pub fn parse(
  body: BitArray,
  content_type: String,
  limits: Limits,
) -> Result(List(Part), MultipartError)

Parses a whole multipart body.

content_type is the HTTP Content-Type value with its boundary parameter. The preamble before the first boundary and the epilogue after the last one are ignored. Lines may end in CRLF or LF, and a header line that starts with a space or tab continues the one before it.

The Content-Type is checked first: InvalidContentType, then UnsupportedMediaType, MissingBoundary and InvalidBoundary. Then the body may fail with UnexpectedEndOfInput, InvalidHeader, InvalidContentDisposition, InvalidQuotedPair or one of the limit errors. The body is read up to max_body_bytes and the first problem in it is reported, so a body that is too large but has a bad header before the limit fails with the header error, as in stream.parse.

Examples

let body = <<
  "--b\r\n",
  "Content-Disposition: form-data; name=\"title\"\r\n\r\n",
  "hello\r\n",
  "--b--\r\n",
>>
let assert Ok(parts) =
  parse(body, "multipart/form-data; boundary=b", default_limits)
field(parts, "title")
// -> Ok("hello")
parse(<<>>, "application/json", default_limits)
// -> Error(UnsupportedMediaType("application/json"))
pub fn parse_content_disposition(
  value: String,
) -> Result(ContentDisposition, MultipartError)

Parses a Content-Disposition header value.

parse already reads the field name and filename of each part, so this is for other uses, such as the attachment parts of a multipart/mixed body.

Parameter names ignore case, and whitespace may surround =.

A filename* (or name*) that is not RFC 5987 UTF-8 or ISO-8859-1, or that decodes to CR, LF or NUL, is ignored, and filename is used.

Returns Error(InvalidQuotedPair(value)) when a quoted string escapes a control character, and Error(InvalidContentDisposition(value)) for any other malformed value, including a parameter given twice.

Examples

parse_content_disposition("attachment; filename=\"a.txt\"")
// -> Ok(ContentDisposition(
//   disposition: "attachment",
//   name: None,
//   filename: Some("a.txt"),
//   parameters: [#("filename", "a.txt")],
// ))
parse_content_disposition("; name=x")
// -> Error(InvalidContentDisposition("; name=x"))
✨ Search Document