I am creating a static file server in Clojure with Compojure, and I am stuck when reading an image from the file system and showing this image along the Compojure route.
slurp, unfortunately, does not handle binary data very well, and since then I have tried this in 100 different ways, but this is my last unsuccessful attempt:
(defn image-output [filepath] (try (let [contents (apply str (with-open [rdr (io/reader filepath)] (into #{} (line-seq rdr))))] { :status 200 :headers { "Content-Type" "image/jpeg", "Content-Length" "", "Cache-Control" "", "Expires" "" } :body contents })) (catch Exception e {:status 404}))) (defn endpoint_view [params] (if (contains? params :bucket) (image-output (join "/" [data_path (:bucket params) (:dir params) (:filename params)])))) (defroutes main-routes (GET "/view/:bucket/:dir/:filename" {params :params} (endpoint_view params)) (route/files "/") (route/resources "/s" {:root "./public/s"}) (route/not-found "Page not found"))
This current attempt seems to be experiencing the same fate as using slurp, where I can repeat the content string and its and the encoded string, but when I change the content type to image / jpeg, this is a broken image.
Yesterday I spent all day Google, but none of the examples reached the same goal, and although they helped me understand a little more about Java IO, they were not clear enough to help me get to where I needed to go, or got same results as me (for example: The best way to read the contents of a file in a set in Clojure ).
(Imaginary bonus points, if you can tell me how to get the type of content from the file path, as well as my next question!)
source share