422在Clojure中POST文件上载时无法处理的实体响应

时间:2016-12-20 23:53:53

标签: clojure compojure clj-http

我试图模仿这个卷曲请求

<script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>

<select id="fac_name">
  <option value="1" selected>Name1</option>
  <option value="2">Name1</option>
  <option value="other">other</option>
</select>

<div id="otherFAC">I should be hidden when page loads if 'other' is not selected when the page loads</div>

使用以下代码

curl "https://{subdomain}.zendesk.com/api/v2/uploads.json?filename=myfile.dat&token={optional_token}" \
  -v -u {email_address}:{password} \
  -H "Content-Type: application/binary" \
  --data-binary @file.dat -X POST

但是我从Zendesk获得了'422 Unprocessable Entity'回复。文件/ tempfile在请求中以 (POST "/uploads" request (let [filename (get-in request [:params "file" :filename]) file (get-in request [:params "file" :tempfile]) url (str "https://REDACTED.zendesk.com/api/v2/uploads.json?filename=" filename)] (clj-http.client/post url {:headers {"Content-Type" “application/binary”} :multipart-params [{:name "file" :content file :mime-type "application/binary”}]}) 形式出现。

我使用了Saving an image form clj-http request to file中提到的clojure.java.io强制(如#object[java.io.File 0x3768306f "/var/folders/l3/7by17gp51sx2gb2ggykwl9zc0000gn/T/ring-multipart-6501654841068837352.tmp"]),但这并没有帮助。

(PS。我很确定我不需要授权,因为我可以直接上传到Zendesk通过Postman工作。)

1 个答案:

答案 0 :(得分:0)

重新审视之后,解决方案很简单。 Zendesk期望请求体是二进制的(如curl请求所示)。因此,在这种情况下,我将图像作为base64编码数据传递给我的服务器(就像JSON一样)。

然后我使用这个库将base64字符串转换为字节数组:https://github.com/xsc/base64-clj

(defn byte-array-from-base64
  [base64-string]
  (base64/decode-bytes (.getBytes base64-string)))

最后,您可以简单地将字节数组作为clj-http库请求的主体传递给Zendesk。

(client/post
  "https://REDACTED.zendesk.com/api/v2/uploads.jsonfilename=filename.jpg"
  {:headers {"Authorization" "Basic AUTHORIZATION_TOKEN"
             "Content-Type" "application/binary"}
   :body (byte-array-from-base64 base64-string)})