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
nameparameter. - filename
-
The
filename*parameter decoded from RFC 5987 form when present, otherwise thefilenameparameter. - 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(String)
InvalidBoundary(String)
UnsupportedMediaType(String)
InvalidHeader(String)
InvalidContentDisposition(String)
InvalidQuotedPair(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(String)
}
Constructors
-
MissingBoundaryThe Content-Type has no
boundaryparameter. -
InvalidContentType(String)The Content-Type is not a media type with parameters.
-
InvalidBoundary(String)The boundary is empty, longer than 70 characters, ends in a space or contains a character RFC 2046 does not allow.
-
UnsupportedMediaType(String)The media type is not
multipart/*. -
InvalidHeader(String)A header line is folded, has no
:or has an empty name. It holds the line, or""when the header block is not UTF-8. -
InvalidContentDisposition(String)A
Content-Dispositionvalue could not be parsed. It holds the value. -
InvalidQuotedPair(String)A
Content-Dispositionquoted string escapes a control character, as in\followed by NUL. It holds the value. -
UnexpectedEndOfInputThe 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_partis empty, starts with a space or tab, or contains CR, LF, NUL or:. -
InvalidHeaderValue(name: String, value: String)A header value given to
new_part, or a name, filename or content type given tonew_fieldornew_file, contains CR, LF or NUL. -
EmptyFieldName(name: String)The field name given to
new_fieldornew_fileis empty or only whitespace. -
MissingField(name: String)fieldfound no text field with this name. -
InvalidUtf8Field(name: String)fieldfound the text field, but its body is not UTF-8. -
MissingFile(name: String)filefound no file part with this name. -
DisallowedContentType(String)allowed_content_typesrejected the part’s Content-Type. It holds the Content-Type, or""when the part has none.
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 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. 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.
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.
A filename that is not printable ASCII is also written in RFC 5987
filename* form, so it survives the round trip through parse. 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,
starts with a space or tab, or contains CR, LF, NUL or :. 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.
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.
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.
Returns Error(InvalidQuotedPair(value)) when a quoted string escapes a
control character, and Error(InvalidContentDisposition(value)) for any
other malformed value, including a filename* that is not valid UTF-8 or
ISO-8859-1 or decodes to CR, LF or NUL.
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"))