Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@matstani
Last active December 14, 2015 09:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matstani/5064493 to your computer and use it in GitHub Desktop.
Save matstani/5064493 to your computer and use it in GitHub Desktop.
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