2016-12-20 46 views
2
執行POST文件上傳時

我試圖模仿這種捲曲請求422無法處理的實體響應Clojure中

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 

用下面的代碼

(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」}]}) 

,但我得到一個「422無法處理的實體」響應來自Zendesk。文件/ tempfile在請求中以#object[java.io.File 0x3768306f "/var/folders/l3/7by17gp51sx2gb2ggykwl9zc0000gn/T/ring-multipart-6501654841068837352.tmp"]的形式出現。

我玩過clojure.java.io強制(如clojure.java.io/output-stream),如Saving an image form clj-http request to file所述,但這並沒有幫助。

(PS。我相當肯定我不需要權威性,因爲我能得到直接上傳到的Zendesk通過郵差的工作。)

回答

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

最後,你可以簡單的通過將字節數組的Zendesk作爲CLJ-HTTP庫請求的主體。

(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)}) 
相關問題