forked from ymasory/scalatra-website-examples
/
FileUploadExample.scala
51 lines (42 loc) · 1.48 KB
/
FileUploadExample.scala
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package org.scalatra.example
import org.scalatra._
import servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException}
import xml.{Elem, Node}
class FileUploadExample extends ScalatraServlet with FileUploadSupport with FlashMapSupport {
configureMultipartHandling(MultipartConfig(maxFileSize = Some(3*1024*1024)))
def displayPage(content: Seq[Node]): Elem = Template.page("File upload example", content, url(_))
error {
case e: SizeConstraintExceededException =>
RequestEntityTooLarge(displayPage(
<p>The file you uploaded exceeded the 3 MB limit.</p>))
}
get("/") {
displayPage(
<form action={url("/")} method="post" enctype="multipart/form-data">
<p>File to upload: <input type="file" name="file" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
<p>
Upload a file using the above form. After you hit "Upload"
the file will be uploaded and your browser will start
downloading it.
</p>
<p>
The maximum file size accepted is 3 MB.
</p>)
}
post("/") {
fileParams.get("file") match {
case Some(file) =>
Ok(file.get(), Map(
"Content-Type" -> file.contentType.getOrElse("application/octet-stream"),
"Content-Disposition" -> ("attachment; filename=\"" + file.name + "\"")
))
case None =>
BadRequest(displayPage(
<p>
Hey! You forgot to select a file.
</p>))
}
}
}