环形中间件不提取多部分参数

multipart-params are not extracted by ring-middleware

我目前在 Clojure 中上传 multipart/form-data 时遇到问题,因此我尝试创建一个最小示例来验证它们。我用 lein new compojure multipart-upload.

创建了一个新项目

以下代码在处理程序 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))))

我还创建了我要上传的文件 a.txt

--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--

然后我运行这个curl命令:

curl -X POST -H "Content-type: multipart/form-data; boundary=--ABC" --data-binary @a.txt http://localhost:3000/

我希望请求映射中的 :multipart-params 键包含我的数据,但我只看到:

{: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}

如何将多部分参数提取到请求映射中,我的错误是什么?

您应该使用 wrap-multipart-params 中间件

 (use 'ring.middleware.multipart-params)

 (def app (-> app-routes
              log-requests 
              wrap-defaults
              api-defaults
              wrap-multipart-params))

然后就可以访问请求的:params属性中的所有参数了。

   (POST "/your-route" request 
         (let [description (get (:params request) "description")]
                ...