Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fetch & write a binary file using Clojure and clj-http
(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)))))
@benwhorwood

This comment has been minimized.

Show comment
Hide comment
@benwhorwood

benwhorwood Feb 15, 2017

Thanks, just what I needed for downloading and writing images from the PrestaShop web service.

benwhorwood commented Feb 15, 2017

Thanks, just what I needed for downloading and writing images from the PrestaShop web service.

@hgalant

This comment has been minimized.

Show comment
Hide comment
@hgalant

hgalant Jun 23, 2017

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 with clojure.java.io/copy:

(defn- save-photo!
  "downloads and stores the photo on disk"
  [{:keys [url id] :as photo}]
 (some-> (fetch-photo! url) (io/copy (io/file "photos" id ".jpg"))))

Did not test, but looks okay.

hgalant commented Jun 23, 2017

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 with clojure.java.io/copy:

(defn- save-photo!
  "downloads and stores the photo on disk"
  [{:keys [url id] :as photo}]
 (some-> (fetch-photo! url) (io/copy (io/file "photos" id ".jpg"))))

Did not test, but looks okay.

@trickyBytes

This comment has been minimized.

Show comment
Hide comment
@trickyBytes

trickyBytes Aug 3, 2017

Great, thanks!

trickyBytes commented Aug 3, 2017

Great, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment