Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

clojure - Saving an image form clj-http request to file

I am trying to save a file downloaded using clj-http

I have the following code:

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

and when I try to make it as a byte-array, I get an exception:

       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)

Help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use binary output.

(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: output-stream is better:

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

Update:

a elegant way:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...