19

How do you download an image from the web and save it to your file system using Clojure? I know the image url and I'm aware that I can't use spit and slurp to do this because it's binary data, not text.

I'd like to do this as simply as possible, ideally like how spit and slurp work. That is, without a lot of extra lines using buffers or byte arrays. I want to close the streams when I'm done, but I don't care if it's inefficient.

Dave Liepmann
  • 1,555
  • 1
  • 18
  • 22
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • Duplicate of [this question](http://stackoverflow.com/questions/11321264/saving-an-image-form-clj-http-request-to-file). Answered via IRC. – arrdem Mar 26 '13 at 03:14
  • 3
    I'm going to leave this here so that google can find this better. I did a google search first and couldn't find an answer. – Daniel Kaplan Mar 26 '13 at 03:40
  • 4
    Though in practice the solutions to these two questions are nearly identical, this question is more general in that it doesn't involve `clj-http` to get the file. Therefore I don't think it should be closed as a duplicate. – Dave Liepmann Oct 10 '13 at 19:57

1 Answers1

29

Zhitong He pointed me to this solution, which worked best for my purposes:

 (defn copy [uri file]
  (with-open [in (io/input-stream uri)
              out (io/output-stream file)]
    (io/copy in out)))

As Zhitong notes, you'll need (:require [clojure.java.io :as io]) in your namespace to use this as coded. Alternatively, you could refer to clojure.java.io directly:

(defn copy-uri-to-file [uri file]
  (with-open [in (clojure.java.io/input-stream uri)
              out (clojure.java.io/output-stream file)]
    (clojure.java.io/copy in out)))
Dave Liepmann
  • 1,555
  • 1
  • 18
  • 22