Download frontend generated data to a file with clojurescript

I had to write this because I couldn't find it with a quick search, so here it his for future people like me (or me).

This is how you allow users to download a file from data generated in the browser with the save file dialog in cljs:

(defn to-json [v] (.stringify js/JSON v))

(defn download-object-as-json [value export-name]
        (let [data-blob (js/Blob. #js [(to-json value)] #js {:type "application/json"})
                  link (.createElement js/document "a")]
          (set! (.-href link) (.createObjectURL js/URL data-blob))
          (.setAttribute link "download" export-name)
          (.appendChild (.-body js/document) link)
          (.click link)
          (.removeChild (.-body js/document) link)))

You call it like this:

(download-object-as-json (clj->js {:hello "world"}) "myfile.json")

As an extra, it shows many idioms to interoperate with js and js objects.

Comentarios

Comments powered by Disqus