Sunday, December 30, 2012

Handling a form with an image and multiple other fields in Play (Scala)

File upload along with other data is a common scenario. This can be handled in Play framework in different ways. 

One case is where Play Forms are used. (refer Play Documentation)
Another case is using custom forms and Play Framework as backend.  (An example function definition)

The file can be accessed using 

request.body.file("fileName")

and in the second case, the fields can be accessed using 

(request.body).asFormUrlEncoded.get("fieldName").get(0)

asFormUrlEncoded returns a Map[ String, Seq [ String ] ] Object. Thus, in order to get the value of a parameter we need to use get(0). 


Note: while using Play Form, it is better to complete the data transactions and handle file upload in its success call

signupForm.bindFromRequest.fold(
  formWithErrors => BadRequest(html.register(formWithErrors)),
  user => {
    request.body.file("picture").map {
      picture =>
        val fileName = user._1
        val path="/path/to/destination/"
        ...

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.