FileUploadSupport

trait FileUploadSupport extends ServletBase with HasMultipartConfig

FileUploadSupport can be mixed into a org.scalatra.ScalatraFilter or org.scalatra.ScalatraServlet to provide easy access to data submitted as part of a multipart HTTP request. Commonly this is used for retrieving uploaded files.

Once the trait has been mixed into your handler, you need to enable multipart configuration in your ''web.xml'' or by using @MultipartConfig annotation. To configure in ''web.xml'' add <multipart-config /> to your <servlet> element. If you prefer annotations instead, place @MultipartConfig to your handler. Both ways provide some further configuration options, such as specifying the max total request size and max size for invidual files in the request. You might want to set these to prevent users from uploading too large files.

When the configuration has been done, you can access any files using fileParams("myFile") where ''myFile'' is the name of the parameter used to upload the file being retrieved. If you are expecting multiple files with the same name, you can use fileMultiParams("files[]") to access them all.

To handle any errors that are caused by multipart handling, you need to configure an error handler to your handler class:

import org.scalatra.servlet.SizeLimitExceededException
import org.scalatra.servlet.FileUploadSupport

@MultipartConfig(maxFileSize=1024*1024)
class FileEaterServlet extends ScalatraServlet with FileUploadSupport {
 error {
   case e: SizeConstraintExceededException => "Oh, too much! Can't take it all."
   case e: IOException                     => "Server denied me my meal, thanks anyway."
 }

 post("/eatfile") {
   "Thanks! You just provided me " + fileParams("lunch").size + " bytes for a lunch."
 }
}

}}* @note Once any handler with FileUploadSupport has accessed the request, the fileParams returned by FileUploadSupport will remain fixed for the lifetime of the request.

Note:

Will not work on Jetty versions prior to 8.1.3. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=376324. The old scalatra-fileupload module still works for earlier versions of Jetty.

Companion:
object
trait HasMultipartConfig
trait Initializable
trait CoreDsl
trait Control
trait Handler
class Object
trait Matchable
class Any

Type members

Inherited classlikes

trait Config
Inherited from:
Initializable

Inherited types

type ConfigT <: { def getServletContext(): ServletContext; def getInitParameter(name: String): String; def getInitParameterNames(): Enumeration[String]; }
Inherited from:
ServletBase

Value members

Concrete methods

def fileMultiParams(implicit request: HttpServletRequest): FileMultiParams
def fileMultiParams(key: String)(implicit request: HttpServletRequest): Seq[FileItem]
def fileParams(implicit request: HttpServletRequest): FileSingleParams
Returns:

a Map, keyed on the names of multipart file upload parameters, of all multipart files submitted with the request

def fileParams(key: String)(implicit request: HttpServletRequest): FileItem
override def handle(req: HttpServletRequest, res: HttpServletResponse): Unit

Handles a request and renders a response.

Handles a request and renders a response.

$ 1. If the request lacks a character encoding, defaultCharacterEncoding is set to the request.

$ 2. Sets the response's character encoding to defaultCharacterEncoding.

$ 3. Binds the current request, response, and multiParams, and calls executeRoutes().

Definition Classes

Inherited methods

def after(transformers: RouteTransformer*)(fun: => Any): Unit

Adds a filter to run after the route. The filter only runs if each routeMatcher returns Some. If the routeMatchers list is empty, the filter runs for all routes.

Adds a filter to run after the route. The filter only runs if each routeMatcher returns Some. If the routeMatchers list is empty, the filter runs for all routes.

Inherited from:
ScalatraBase
def before(transformers: RouteTransformer*)(fun: => Any): Unit

Adds a filter to run before the route. The filter only runs if each routeMatcher returns Some. If the routeMatchers list is empty, the filter runs for all routes.

Adds a filter to run before the route. The filter only runs if each routeMatcher returns Some. If the routeMatchers list is empty, the filter runs for all routes.

Inherited from:
ScalatraBase
def configureMultipartHandling(config: MultipartConfig): Unit
Inherited from:
HasMultipartConfig
def contentType: String

Gets the content type of the current response.

Gets the content type of the current response.

Inherited from:
ScalatraContext
def contentType_=(contentType: String): Unit

Sets the content type of the current response.

Sets the content type of the current response.

Inherited from:
ScalatraContext
def cookies(implicit request: HttpServletRequest): SweetCookies
Inherited from:
CookieContext
def delete(transformers: RouteTransformer*)(action: => Any): Route
See also:

get

Inherited from:
ScalatraBase
def environment: String
Inherited from:
ScalatraBase
def error(handler: ErrorHandler): Unit

Defines an error handler for exceptions thrown in either the before block or a route action.

Defines an error handler for exceptions thrown in either the before block or a route action.

If the error handler does not match, the result falls through to the previously defined error handler. The default error handler simply rethrows the exception.

The error handler is run before the after filters, and the result is rendered like a standard response. It is the error handler's responsibility to set any appropriate status code.

Inherited from:
ScalatraBase
def format_=(formatValue: String): Unit

Explicitly sets the request-scoped format. This takes precedence over whatever was inferred from the request.

Explicitly sets the request-scoped format. This takes precedence over whatever was inferred from the request.

Inherited from:
ScalatraContext
def format_=(formatValue: Symbol): Unit

Explicitly sets the request-scoped format. This takes precedence over whatever was inferred from the request.

Explicitly sets the request-scoped format. This takes precedence over whatever was inferred from the request.

Inherited from:
ScalatraContext
def fullUrl(path: String, params: Iterable[(String, Any)], includeContextPath: Boolean, includeServletPath: Boolean, withSessionId: Boolean)(implicit request: HttpServletRequest, response: HttpServletResponse): String

Builds a full URL from the given relative path. Takes into account the port configuration, https, ...

Builds a full URL from the given relative path. Takes into account the port configuration, https, ...

Value parameters:
path

a relative path

Returns:

the full URL

Inherited from:
ScalatraBase
def get(transformers: RouteTransformer*)(action: => Any): Route

The Scalatra DSL core methods take a list of org.scalatra.RouteMatcher and a block as the action body. The return value of the block is rendered through the pipeline and sent to the client as the response body.

The Scalatra DSL core methods take a list of org.scalatra.RouteMatcher and a block as the action body. The return value of the block is rendered through the pipeline and sent to the client as the response body.

See org.scalatra.ScalatraBase#renderResponseBody for the detailed behaviour and how to handle your response body more explicitly, and see how different return types are handled.

The block is executed in the context of a CoreDsl instance, so all the methods defined in this trait are also available inside the block.

 get("/") {
   <form action="/echo">
     <label>Enter your name</label>
     <input type="text" name="name"/>
   </form>
 }

 post("/echo") {
   "hello {params('name)}!"
 }

ScalatraKernel provides implicit transformation from boolean blocks, strings and regular expressions to org.scalatra.RouteMatcher, so you can write code naturally.

 get("/", request.getRemoteHost == "127.0.0.1") { "Hello localhost!" }
Inherited from:
ScalatraBase
def halt(result: ActionResult): Nothing
Inherited from:
Control
def halt[T](status: Integer, body: T, headers: Map[String, String]): Nothing

Immediately halts processing of a request. Can be called from either a before filter or a route.

Immediately halts processing of a request. Can be called from either a before filter or a route.

Value parameters:
body

a result to render through the render pipeline as the body

headers

headers to add to the response

status

the status to set on the response, or null to leave the status unchanged.

Inherited from:
Control
def head(transformers: RouteTransformer*)(action: => Any): Route
See also:

head

Inherited from:
ScalatraBase
def initParameter(name: String): Option[String]

Gets an init parameter from the config.

Gets an init parameter from the config.

Value parameters:
name

the name of the key

Returns:

an option containing the value of the parameter if defined, or None if the parameter is not set.

Inherited from:
ScalatraBase
def initialize(config: ConfigT): Unit

A hook to initialize the class with some configuration after it has been constructed.

A hook to initialize the class with some configuration after it has been constructed.

Not called init because GenericServlet doesn't override it, and then we get into https://lampsvn.epfl.ch/trac/scala/ticket/2497.

Inherited from:
HasMultipartConfig
def isDevelopmentMode: Boolean

A boolean flag representing whether the kernel is in development mode. The default is true if the environment begins with "dev", case-insensitive.

A boolean flag representing whether the kernel is in development mode. The default is true if the environment begins with "dev", case-insensitive.

Inherited from:
ScalatraBase
def methodNotAllowed(f: Set[HttpMethod] => Any): Unit

Defines a block to run if matching routes are found only for other methods. The set of matching methods is passed to the block.

Defines a block to run if matching routes are found only for other methods. The set of matching methods is passed to the block.

Inherited from:
ScalatraBase
def multiParams(implicit request: HttpServletRequest): MultiParams

The current multiparams. Multiparams are a result of merging the standard request params (query string or post params) with the route parameters extracted from the route matchers of the current route. The default value for an unknown param is the empty sequence. Invalid outside handle.

The current multiparams. Multiparams are a result of merging the standard request params (query string or post params) with the route parameters extracted from the route matchers of the current route. The default value for an unknown param is the empty sequence. Invalid outside handle.

Inherited from:
ScalatraBase
def multiParams(key: String)(implicit request: HttpServletRequest): Seq[String]
Inherited from:
ScalatraBase
def multipartConfig: MultipartConfig
Inherited from:
HasMultipartConfig
def notFound(fun: => Any): Unit

Defines a block to run if no matching routes are found, or if all matching routes pass.

Defines a block to run if no matching routes are found, or if all matching routes pass.

Inherited from:
ScalatraBase
def options(transformers: RouteTransformer*)(action: => Any): Route
See also:

get

Inherited from:
ScalatraBase
def params(implicit request: HttpServletRequest): Params
Inherited from:
ScalatraBase
def params(key: String)(implicit request: HttpServletRequest): String
Inherited from:
ScalatraBase
def pass(): Nothing

Immediately exits from the current route.

Immediately exits from the current route.

Inherited from:
Control
def patch(transformers: RouteTransformer*)(action: => Any): Route
See also:

patch

Inherited from:
ScalatraBase
def post(transformers: RouteTransformer*)(action: => Any): Route
See also:

get

Inherited from:
ScalatraBase
def put(transformers: RouteTransformer*)(action: => Any): Route
See also:

get

Inherited from:
ScalatraBase
def redirect(uri: String)(implicit request: HttpServletRequest, response: HttpServletResponse): Nothing

Sends a redirect response and immediately halts the current action.

Sends a redirect response and immediately halts the current action.

Inherited from:
ScalatraBase
def relativeUrl(path: String, params: Iterable[(String, Any)], includeContextPath: Boolean, includeServletPath: Boolean)(implicit request: HttpServletRequest, response: HttpServletResponse): String
Inherited from:
ScalatraBase
def requestPath(implicit request: HttpServletRequest): String

The effective path against which routes are matched. The definition varies between servlets and filters.

The effective path against which routes are matched. The definition varies between servlets and filters.

Inherited from:
ScalatraBase
def serverHost(implicit request: HttpServletRequest): String
Inherited from:
ScalatraBase
def serverPort(implicit request: HttpServletRequest): Int
Inherited from:
ScalatraBase
def servletContext: ServletContext

The servlet context in which this kernel runs.

The servlet context in which this kernel runs.

Inherited from:
ScalatraBase
def session(key: String)(implicit request: HttpServletRequest): Any
Inherited from:
SessionSupport
def sessionOption(implicit request: HttpServletRequest): Option[HttpSession]

The current session. If none exists, None is returned.

The current session. If none exists, None is returned.

Inherited from:
SessionSupport
protected def shutdown(): Unit

A hook to shutdown the class. Bridges the gap between servlet's destroy and filter's destroy.

A hook to shutdown the class. Bridges the gap between servlet's destroy and filter's destroy.

Inherited from:
Initializable
def status: Int

Gets the status code of the current response.

Gets the status code of the current response.

Inherited from:
ScalatraContext
def status_=(code: Int): Unit

Sets the status code of the current response.

Sets the status code of the current response.

Inherited from:
ScalatraContext
def stringToDate(format: => String): TypeConverter[String, Date]
def stringToDateFormat(format: => DateFormat): TypeConverter[String, Date]
def stringToSeq[T : ClassTag](elementConverter: TypeConverter[String, T], separator: String): TypeConverter[String, Seq[T]]
def trap(codes: Range)(block: => Any): Unit

Error handler for HTTP response status code range. You can intercept every response code previously specified with #status or even generic 404 error.

Error handler for HTTP response status code range. You can intercept every response code previously specified with #status or even generic 404 error.

 trap(403) {
  "You are not authorized"
 }
}* 

}}

Inherited from:
ScalatraBase
def trap(code: Int)(block: => Any): Unit
See also:

error

Inherited from:
CoreDsl
def url(path: String, params: Iterable[(String, Any)], includeContextPath: Boolean, includeServletPath: Boolean, absolutize: Boolean, withSessionId: Boolean)(implicit request: HttpServletRequest, response: HttpServletResponse): String

Returns a context-relative, session-aware URL for a path and specified parameters. Finally, the result is run through response.encodeURL for a session ID, if necessary.

Returns a context-relative, session-aware URL for a path and specified parameters. Finally, the result is run through response.encodeURL for a session ID, if necessary.

Value parameters:
params

params, to be appended in the form of a query string

path

the base path. If a path begins with '/', then the context path will be prepended to the result

Returns:

the path plus the query string, if any. The path is run through response.encodeURL to add any necessary session tracking parameters.

Inherited from:
ScalatraBase
protected def withRequest[A](request: HttpServletRequest)(f: => A): A

Executes the block with the given request bound to the request method.

Executes the block with the given request bound to the request method.

Inherited from:
DynamicScope
protected def withResponse[A](response: HttpServletResponse)(f: => A): A

Executes the block with the given response bound to the response method.

Executes the block with the given response bound to the response method.

Inherited from:
DynamicScope

Inherited fields

The configuration, typically a ServletConfig or FilterConfig.

The configuration, typically a ServletConfig or FilterConfig.

Inherited from:
ScalatraBase

The routes registered in this kernel.

The routes registered in this kernel.

Inherited from:
ScalatraBase

Implicits

Inherited implicits

implicit val anyToBoolean: TypeConverter[Any, Boolean]
implicit val anyToByte: TypeConverter[Any, Byte]
implicit val anyToDouble: TypeConverter[Any, Double]
implicit val anyToFloat: TypeConverter[Any, Float]
implicit val anyToInt: TypeConverter[Any, Int]
implicit val anyToLong: TypeConverter[Any, Long]
implicit val anyToShort: TypeConverter[Any, Short]
implicit val anyToString: TypeConverter[Any, String]
implicit protected def configWrapper(config: ConfigT): Config
Inherited from:
ServletBase
Inherited from:
CookieContext
implicit def defaultStringToSeq[T : ClassTag](implicit evidence$1: ClassTag[T], elementConverter: TypeConverter[String, T]): TypeConverter[String, Seq[T]]
implicit def enrichRequest(request: HttpServletRequest): RichRequest
Inherited from:
ServletApiImplicits
implicit def enrichResponse(response: HttpServletResponse): RichResponse
Inherited from:
ServletApiImplicits
implicit def enrichServletContext(servletContext: ServletContext): RichServletContext
Inherited from:
ServletApiImplicits
implicit def enrichSession(session: HttpSession): RichSession
Inherited from:
ServletApiImplicits
implicit def lowestPriorityAny2T[T : ClassTag]: TypeConverter[Any, T]
implicit def request: HttpServletRequest

The currently scoped request. Valid only inside the handle method.

The currently scoped request. Valid only inside the handle method.

Inherited from:
DynamicScope
implicit def response: HttpServletResponse

The currently scoped response. Valid only inside the handle method.

The currently scoped response. Valid only inside the handle method.

Inherited from:
DynamicScope
implicit def safe[S, T](f: S => T): TypeConverter[S, T]
Inherited from:
TypeConverterSupport
implicit def safeOption[S, T](f: S => Option[T]): TypeConverter[S, T]

Implicit convert a (String) => Option[T] function into a TypeConverter[T]

Implicit convert a (String) => Option[T] function into a TypeConverter[T]

Inherited from:
TypeConverterSupport
implicit def seqHead[T : ClassTag](implicit evidence$3: ClassTag[T], elementConverter: TypeConverter[String, T]): TypeConverter[Seq[String], T]
implicit def seqToSeq[T : ClassTag](implicit evidence$4: ClassTag[T], elementConverter: TypeConverter[String, T]): TypeConverter[Seq[String], Seq[T]]
implicit def session(implicit request: HttpServletRequest): HttpSession

The current session. Creates a session if none exists.

The current session. Creates a session if none exists.

Inherited from:
SessionSupport
implicit val stringToBoolean: TypeConverter[String, Boolean]
implicit val stringToByte: TypeConverter[String, Byte]
implicit val stringToDouble: TypeConverter[String, Double]
implicit val stringToFloat: TypeConverter[String, Float]
implicit val stringToInt: TypeConverter[String, Int]
implicit val stringToLong: TypeConverter[String, Long]
implicit val stringToSelf: TypeConverter[String, String]
implicit val stringToShort: TypeConverter[String, Short]
implicit def toTypedParams(params: Params): TypedParams