2012-07-04 28 views
16

Tôi cố gắng để lưu một tập tin dữ liệu qua clj-httpTiết kiệm một hình thức hình ảnh theo yêu cầu CLJ-http nộp

Tôi có đoạn mã sau:

(def test-file 
    (cl/get "http://placehold.it/350x150")) 

(defn write-file [] 
    (with-open [w (clojure.java.io/writer "test-file.gif" :append true)] 
(.write w (:body test-file)))) 

và khi tôi cố gắng làm cho nó như là một byte -array, tôi có ngoại lệ:

 user=>  (def test-file 
        (cl/get "http://placehold.it/350x150" {:as :byte-array})) 
     #'user/test-file 
     user=> (write-file) 
     IllegalArgumentException No matching method found: write for class java.io.BufferedWriter clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:79) 

Trợ giúp!

+0

Mặc dù bạn có thể sử dụng CLJ-http , điều này có thể được thực hiện hoàn toàn bằng c lojure.java.io: http://stackoverflow.com/q/15628682/425313 –

Trả lời

25

sử dụng đầu ra nhị phân.

(def test-file 
    (client/get "http://placehold.it/350x150" {:as :byte-array})) 

(defn write-file [] 
    (with-open [w (java.io.BufferedOutputStream. (java.io.FileOutputStream. "test-file.gif"))] 
    (.write w (:body test-file)))) 

Edit: sản lượng dòng là tốt hơn:

(defn write-file [] 
    (with-open [w (clojure.java.io/output-stream "test-file.gif")] 
    (.write w (:body test-file)))) 

Cập nhật:

một cách tao nhã:

(clojure.java.io/copy 
(:body (client/get "http://placehold.it/350x150" {:as :stream})) 
(java.io.File. "test-file.gif")) 
+0

tuyệt vời! nó làm việc cho tôi – zcaudate

+0

Thêm vào điểm, writer.write mong char [] và outputstream.write mong đợi byte [] – Kevin

+5

Nhưng bạn có lẽ nên sử dụng clojure.java.io/output-stream – Kevin

Các vấn đề liên quan