I want to upload an image, show a preview of the image, and the associated filename, all in Clojure.
The example at http://jsfiddle.net/LvsYc/638/ demonstrates what I want to do, except I want it in Clojure/ClojureScript.
I have attempted to rewrite the code from the above link, and have managed to output the file-name to the console using (js/console.log). I have two global atoms in my file, one for the image name, and one for the image itself. My code below is my attempt so far.
What do I need to do to 1). get the name of the file from the console log and display it in the :span.file-name using these atoms, and 2), display a preview of the image?
(def image (atom "#"))
(def image-name (atom nil))
(def file-upload-selector
"Implements a file-upload button, allowing the user to
navigate to a file on their desktop and select it."
(let
[reader (js/FileReader.)
_ (set! (.-onload reader)
(fn [e]
(reset! image
(-> e .-target .-result ))))
read-url
(fn [input]
(reset! image-name (-> input .-target .-files (aget 0) .-name))
(js/console.log (-> input .-target .-files (aget 0) .-name))
(when-let [file-input (.-files input)]
(.readAsDataURL reader (aget file-input 0))))]
(fn []
[:div.file.has-name.is-boxed
[:label.file-label
[:input.file-input {:type "file"
:name "User_Photo"
:id "file"
:on-change read-url}]
[:span.file-cta
[:span.file-icon
[:i.fas.fa-upload]]
[:span.file-label "Upload profile picture" ]
][:img {:src image :alt "your image" }]
[:span.file-name {:id "filename" } image-name
]]])))
Found a solution that worked for me. After researching online, the following github link was what I needed.
https://github.com/jlangr/image-upload/blob/master/src/cljs/image_upload/core.cljs
Relevant code from @jlangr.
(let [file (first (array-seq (.. file-added-event -target -files)))
file-reader (js/FileReader.)]
(set! (.-onload file-reader)
(fn [file-load-event]
(reset! preview-src (-> file-load-event .-target .-result))
(let [img (.getElementById js/document img-id)]
(set! (.-onload img)
(fn [image-load]
(.log js/console "dimensions:" (.-width img) "x" (.-height img)))))))
(.readAsDataURL file-reader file)))
(defn image-upload-fn []
[:div [:h2 "image-upload"]
[:input {:type "file" :on-change load-image}]
[:img {:id img-id :src @preview-src}]])