You want to be able to upload files.
We are going to use the filestack service.
Steps
- Sign up and get a free api key
- Create a new project
- Add filestack to
resources/public/index.html
- Add promesa to
project.clj
:dependencies vector - Add promesa to
core.cljs
namespace - Create a button to upload an image,
btn-upload-image
- Add
btn-upload-image
tohome
- Add externs
Go to filestack and create a free account. You will need to create a 'New application' to get an 'API Key'.
$ lein new rc file-upload
<!DOCTYPE html>
<html lang="en">
<body>
<div id="app"></div>
<!-- ATTENTION \/ -->
<script src="https://static.filestackapi.com/v3/filestack.js"></script>
<!-- ATTENTION /\ -->
<script src="js/compiled/app.js"></script>
<script>droppable.core.main();</script>
</body>
</html>
[funcool/promesa "1.8.1"]
Navigate to src/cljs/file_upload/core.cljs
and update the ns
to the following.
(ns file-upload.core
(:require
[reagent.core :as reagent]
[promesa.core :as p]))
The example pick code looks like this:
var client = filestack.init('yourApiKey');
client.pick(pickerOptions);
client.pick({
accept: 'image/*',
maxFiles: 5
}).then(function(result) {
console.log(JSON.stringify(result.filesUploaded))
})
Let's convert this to clojurescript - be sure to use the API Key that you got from step 1.
(defn btn-upload-image []
;; TODO: update XXXX with your api key
(let [client (.init js/filestack "XXXX")]
[:button
{:on-click (fn []
(-> (p/promise
(.pick client (clj->js {:accept "image/*"
:maxFiles 5})))
(p/then #(let [files-uploaded (.-filesUploaded %)
file (aget files-uploaded 0)
file-url (.-url file)]
(js/console.log "URL of file:" file-url)))))}
"Upload Image"]))
(defn home []
[:div
[btn-upload-image]
])
For advanced compilation, we need to protect names used for interop from getting renamed. Add an externs.js
file.
var TopLevel = {
"filestack" : function () {},
"filesUploaded" : function () {},
"init" : function () {},
"log" : function () {},
"pick" : function () {},
"url" : function () {}
}
Open project.clj
and add a reference to the externs in the cljsbuild portion.
:externs ["externs.js"]
Compile cljs files.
$ lein clean
$ lein cljsbuild once prod
Open resources/public/index.html
.
Upload a couple files, then navigate to your app on filestack. You can see the uploaded files under the Assets section.