Created
April 28, 2014 16:35
-
-
Save philippkueng/11377226 to your computer and use it in GitHub Desktop.
Fetch & write a binary file using Clojure and clj-http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns the-namespace.core | |
(:require [clj-http.client :as client] | |
[clojure.java.io :as io])) | |
(defn- fetch-photo! | |
"makes an HTTP request and fetches the binary object" | |
[url] | |
(let [req (client/get url {:as :byte-array :throw-exceptions false})] | |
(if (= (:status req) 200) | |
(:body req)))) | |
(defn- save-photo! | |
"downloads and stores the photo on disk" | |
[photo] | |
(let [p (fetch-photo! (:url photo))] | |
(if (not (nil? p)) | |
(with-open [w (io/output-stream (str "photos/" (:id photo) ".jpg"))] | |
(.write w p))))) |
Great, thanks!
Thank you. Very useful
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not too familiar with
clj-http
but assuming(:body req)
yields a byte-array, as it seems,save-photo!
can be easier and Java-interop-free withclojure.java.io/copy
:Did not test, but looks okay.