02 Sep
Posted by: Nikola Plejić in: (Web) Development, English posts
Compojure is coming to be a really nice framework which is, together with the excellent Enlive templating/transformation library, enough to make this Lisp n00b take a shot at developing a toy project or two in a Lisp dialect. I struggled a bit today to do a file upload: it’s a relatively recent feature in the framework and although it’s pretty straightforward, it took me a while to get it up to speed. Here’s a really basic and primitive example which assumes you have clojure.contrib, Ring, Compojure and Enlive installed.
The key step is to wrap your upload handling route with the wrap-multipart-params middleware from the ring.middleware.multipart-params namespace. The route responsible for the file upload is the latter one:
(defroutes public-routes
(GET "/" [] (render (index)))
(mp/wrap-multipart-params
(POST "/file" {params :params} (upload-file (get params "file")))))
(file in the (get params "file") call is the name of the input field.)
Next, here’s the upload-file handler function called by the route which just takes the file and copies it to a file named file.out in the current project directory:
(defn upload-file
[file]
(ds/copy (file :tempfile) (ds/file-str "file.out"))
(render (upload-success)))
(ds is an alias for the clojure.contrib.duck-streams namespace, and render is a function which takes a template and returns its string representation. upload-success is an Enlive template.)
Voila! Not hard at all. Also check out the gist with complete code and template files.
Nema povezanih postova.
| M | T | W | T | F | S | S |
|---|---|---|---|---|---|---|
| « Mar | ||||||
| 1 | 2 | 3 | 4 | 5 | ||
| 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 27 | 28 | 29 | 30 | 31 | ||
2 Responses
Tweets that mention File upload in Clojure & Compojure by Nikola Plejić -- Topsy.com
02|Sep|2010 1[...] This post was mentioned on Twitter by Nikola Plejic, Javier Neira. Javier Neira said: RT @nikolaplejic: Blogged (it's been a while): File upload in Clojure & Compojure: http://wp.me/phhb8-55 [...]
File uploads with Clojure, Ring and Compojure | ProDevTips - programming tutorials
19|Dec|2010 2[...] just found a great write up on how to upload files by Nikola Plejić. It’s a little bit sparse though so below I’ll revisit it with my own [...]
Leave a reply