An RFC 7578 multipart/form-data parser for Clojure and the Jolt dialect, ported from defnull/multipart. ring-chez-adapter uses it for its multipart middleware, and http-client tests the bodies it builds against it.
Both the incremental push parser and the high-level parse-form-data API are implemented, so you can either stream a request body chunk by chunk or parse it all at once.
Add the git dependency to deps.edn:
{:deps {jolt-lang/multipart
{:git/url "https://github.com/jolt-lang/multipart"
:git/tag "v0.1.2"
:git/sha "<the sha that tag points at>"}}}A git coordinate needs the SHA as well as the tag; read it with
git ls-remote --tags https://github.com/jolt-lang/multipart
Tracking a commit directly works too — :git/sha on its own, no tag. For local
development, a :local/root path:
{:deps {jolt-lang/multipart {:local/root "../multipart"}}}(require '[multipart.core :as multipart])
;; ring-style request map; :body is a byte array, an InputStream or a read-fn
(def request
{:headers {"content-type" "multipart/form-data; boundary=boundary123"}
:body (byte-array (.getBytes (str "--boundary123\r\n"
"Content-Disposition: form-data; name=\"user\"\r\n\r\n"
"alice\r\n"
"--boundary123\r\n"
"Content-Disposition: form-data; name=\"file\"; filename=\"a.txt\"\r\n"
"Content-Type: text/plain\r\n\r\n"
"file contents\r\n"
"--boundary123--")
"UTF-8"))})
(multipart/parse-form-data request)
;; => {:params {"user" "alice"}
;; :files {"file" {:name "file" :filename "a.txt"
;; :content-type "text/plain" :bytes #object["[B" ...]}}}Text fields come back decoded in :params; file uploads in :files, each a map with :name, :filename, :content-type, :charset, :headerlist and :bytes. Multiple values for the same field name are collected into vectors. It also handles application/x-www-form-urlencoded bodies.
multipart/is-form-request? tells you whether a Content-Type value can be parsed this way:
(multipart/is-form-request? "multipart/form-data; boundary=x") ; => true(parse-form-data request & [opts]) → {:params {...} :files {...}}
Parses a ring-style request map (:headers with "content-type", :body with a byte array, a java.io.InputStream or a read-fn). Options:
:charset— default charset for headers and text fields (default"utf-8"):strict— raise on unusual or unsupported input:ignore-errors—truesuppresses all exceptions and returns empty results;falsenever suppresses;nil(default) suppresses in non-strict mode- all
parse-multipartoptions below
(parse-multipart boundary body & [opts]) → vector of part maps
Parses a complete multipart body. boundary is the boundary string; body is a byte array, a java.io.InputStream, or a read-fn of a size argument returning byte arrays (nil at EOF). A stream is wrapped as a read-fn rather than slurped, so it is read no further ahead than the parser asks for. Each part map has :name, :filename, :content-type, :charset, :headerlist and :bytes.
Options, in addition to make-parser's:
:memory-limit— cap on the total payload bytes across all parts (nil= unlimited):check-complete— require the closing--boundary--delimiter (defaulttrue)
RFC 7578 §4.1 requires that delimiter, so a body without one is malformed and the default rejects it. Some servers and clients truncate it, and some parsers accept that; :check-complete false returns the parts that did arrive complete instead of raising. A part whose body was fully received but whose terminator is missing is returned rather than dropped.
(make-parser boundary & opts) → parser map, then feed it to parse-chunk:
(let [parser (multipart/make-parser "boundary123")]
(loop [parser parser, chunk (read-chunk), events []]
(if (empty? chunk)
(do (multipart/close-parser parser) events)
(let [[parser evs] (multipart/parse-chunk parser chunk)]
(recur parser (read-chunk) (into events evs))))))parse-chunk returns [parser events] where events are [:segment segment-map], [:body byte-array] and [:end] — one :segment per part with its parsed headers, zero or more :body events with payload data, and one :end. An empty chunk signals end of input and closes the parser; an incomplete stream raises a ParserError.
parse-stream is the convenience wrapper: (parse-stream parser read-fn & [chunk-size]) returns a lazy seq of the same events, closing the parser at EOF.
make-parser options:
:content-length— expected input size in bytes,-1(default) if unknown:max-header-size— max length of a single header line (default 4224):max-header-count— max headers per segment (default 8):max-segment-size— max size of a single segment body (nil= unlimited):max-segment-count— max number of segments (nil= unlimited):header-charset— charset for header names and values (default"utf-8"):strict— enable additional format and sanity checks
(parse-content-disposition header)→[disposition name filename](parse-options-header header)→[primary-value options-map]— forContent-Type-style headers; passcontent-disposition-unquoteas the unquote fn forContent-Disposition(header-quote s)/(header-unquote s)— quote/unquote RFC 7230 header values(content-disposition-quote s)/(content-disposition-unquote s)— quote/unquote the way browsers do (HTML5 limited percent-encoding), for field names and filenames
Parser failures throw ex-info with a :type key in ex-data; test for them with the predicates multipart-error?, parser-error?, strict-parser-error?, parser-limit-reached? and parser-state-error?.
- The source is split into
multipart.errors(error types),multipart.bytes(byte/ASCII helpers),multipart.headers(header parsing),multipart.parser(the incremental parser) andmultipart.core(high-level API).multipart.corere-exports the public functions of the other namespaces, so requiring justmultipart.coregives you the whole API. - Payloads are always buffered in memory — there is no temp-file spooling.
- The code targets Jolt-compatible Clojure: byte primitives and regex functions are used in their Jolt-safe forms, so the namespace runs under both the JVM and Jolt.
jolt -M:test # or: clojure -M:test
Apache, Version 2.0