2

I'm trying to running some codes from the book "Web development with Clojure". There is a function which I can not understand:

(defn handle-upload [{:keys [filename] :as file}]
  (upload-page 
    (if (empty? filename)
      "please select a file to upload"
      (try 
        (upload-file (gallery-path) file)
        (save-thumbnail file)
        (db/add-image (session/get :user) filename)
        (image {:height "150px"}
          (str "/img/"
               (session/get :user)
               "/"
               thumb-prefix
               (url-encode filename)))
        (catch Exception ex 
          (str "error uploading file " (.getMessage ex)))))))

where

(defn upload-page [info]
    (layout/common
      [:h2 "Upload an image"]
      [:p info]
      (form-to {:enctype "multipart/form-data"}
               [:post "/upload"]
               (file-upload :file)
               (submit-button "upload"))))

What is the meaning of the parameter of the function handle-upload?

And after the changing from

(defn handle-upload [{:keys [filename] :as file}] ...

to

(defn handle-upload [{:keys filename :as file}] ...

I got an error message:

java.lang.IllegalArgumentException: Don't know how to create ISeq from: clojure.lang.Symbol, compiling:(picture_gallery/routes/upload.clj:32:1)

Why?

1 Answer 1

9

{:keys [filename] :as file} means:

  1. Take :filename key from passed argument and bind its value to filename
  2. Leave the whole argument available as file

So if you pass:

{:filename "foo"
 :somethingelse "bar"}

As an argument, then filename in the function scope will be equal to foo and the file will be equal to the whole hash map.

References:

Sign up to request clarification or add additional context in comments.

1 Comment

Also, you can do similar de-structuring with other collection types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.