多部分参数不是由环中间件提取的

时间:2015-11-20 10:16:20

标签: file-upload clojure compojure ring

我目前在Clojure中有多部分/表单数据上传的问题,所以我尝试创建一个最小的例子来验证它们。我用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}

如何将multipart-params提取到请求图中,我的错误是什么?

1 个答案:

答案 0 :(得分:4)

您应该使用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")]
                ...