Skip to content

Firebase: Drop a file to upload it, then display it

Conor White-Sullivan edited this page Apr 29, 2017 · 1 revision
(defn storage-ref [path]
  (.ref (js/firebase.storage) (string/join "/" path)))

(defn handle-file-drop [evt fatom]
  (do (allow-drop evt)
      (.stopPropagation evt)
      (let [f (aget (.. evt -dataTransfer -files) 0)
            fname (.-name f)
            s (storage-ref ["imgs" fname])
            upload-task (.put s f)]
        (.on upload-task "state_changed"
             (fn [snap])
             (fn [error])
             (fn []
               (let [dl (.-downloadURL (.-snapshot upload-task))]
                 (reset! fatom {:url dl
                                :name fname})))))))

(defn allow-drop [e]
  (.preventDefault e))


(defn on-drop
  ([] (on-drop #(js/console.log %)))
  ([dfn]
   {:on-drag-over #(allow-drop %)
    :on-drop dfn
    :on-drag-enter #(allow-drop %)}))


(defn file-upload []
  (r/with-let [fatom (r/atom {:url nil
                              :name nil})]
    [:div.box
     (on-drop #(handle-file-drop % fatom))
     (pr-str @fatom) [:div
                      [:img {:style {:width "400px"}
                             :src (:url @fatom)}]]]))

(defcard fup
  (safe [file-upload]))

Related

  • safe
Clone this wiki locally