I currently have problems with multipart/form-data uploads in Clojure, so I tried to create a minimal example to verify them. I created a new project with lein new compojure multipart-upload
.
The following code is in the handler ns:
(ns multipart-upload.handler
(:require [clojure.pprint :refer [pprint]] [compojure.core :refer :all]
[compojure.route :as route]
[ring.middleware.defaults :refer [wrap-defaults api-defaults]]))
(defroutes app-routes
(POST "/" [] "Hello World")
(route/not-found "Not Found"))
(defn log-request [handler]
(fn [req]
(pprint req)
(handler req)))
(def app
(wrap-defaults (log-request app-routes) (-> api-defaults
(assoc-in [:params :multipart] true)
(assoc-in [:params :nested] true))))
I also created the file a.txt
which I am trying to upload:
--ABC
Content-Disposition: form-data; name="file"; filename="a.txt"
Content-Type: text/plain
A
--ABC
Content-Disposition: form-data; name="description"
test_description
--ABC
Content-Disposition: form-data; name="name"
test_name
--ABC--
Then I run this curl command:
curl -X POST -H "Content-type: multipart/form-data; boundary=--ABC" --data-binary @a.txt http://localhost:3000/
I would expect the :multipart-params
key in the request map to contain my data but I only see:
{:ssl-client-cert nil,
:remote-addr "0:0:0:0:0:0:0:1",
:params {},
:headers
{"host" "localhost:3000",
"accept" "*/*",
"content-length" "241",
"content-type" "multipart/form-data; boundary=--ABC",
"user-agent" "curl/7.37.1"},
:server-port 3000,
:content-length 241,
:form-params {},
:query-params {},
:content-type "multipart/form-data; boundary=--ABC",
:character-encoding nil,
:uri "/",
:server-name "localhost",
:query-string nil,
:body
#object[org.eclipse.jetty.server.HttpInput 0x5f435901 "org.eclipse.jetty.server.HttpInput@5f435901"],
:multipart-params {},
:scheme :http,
:request-method :post}
How can I extract the multipart-params into the request map and what is my error?
You should be using the wrap-multipart-params
middleware
(use 'ring.middleware.multipart-params)
(def app (-> app-routes
log-requests
wrap-defaults
api-defaults
wrap-multipart-params))
Then you can access all the parameters in the :params
attribute of the request.
(POST "/your-route" request
(let [description (get (:params request) "description")]
...