Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compojureでファイルアップロード
(ns helloworld.handler
(:use compojure.core)
(:require [clojure.java.io :as io]
[ring.util.response :as response]
[compojure.handler :as handler]
[compojure.route :as route]
[hiccup.form :as form]
[hiccup.core :refer [html]]))
;; ページレイアウト
(defn layout [& content]
(html
[:head [:title "file upload with compojure."]]
[:body
content]))
;; ファイルアップロード用フォーム
(def upload-form
(layout
(form/form-to
{:enctype "multipart/form-data"}
[:post "/file"]
(form/file-upload "file")
(form/submit-button "submit"))))
;; アップロード成功
(def success
(layout
[:h1 "File uploaded successfully!"]))
;; アップロードされたファイルを保存する
(defn save-file [filename tempfile]
(io/copy tempfile (io/file filename))
(io/delete-file tempfile))
(defroutes app-routes
(GET "/" [] upload-form)
(GET "/success" [] success)
(POST "/file" {{{:keys [filename tempfile]} :file} :params}
(save-file filename tempfile)
(response/redirect "/success"))
(route/not-found "Not Found"))
(def app
(handler/site app-routes))
(defproject helloworld "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:dependencies [[org.clojure/clojure "1.4.0"]
[compojure "1.1.5"]
[hiccup "1.0.2"]]
:plugins [[lein-ring "0.8.2"]]
:ring {:handler helloworld.handler/app}
:profiles
{:dev {:dependencies [[ring-mock "0.1.3"]]}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment