In html, a form with multipart data:
<form action="@routes.Files.upload" method="post" enctype="multipart/form-data">
<input type="hidden" name="groupId" value="1" />
<input type="hidden" name="tagId" value="2" />
<input type="file" name="file"/>
<input type="submit" value="upload it"/>
</form>
How to write the action Files upload
?
I know how to get a uploaded file:
request.body.file("file") map {
filepart => filepart.ref.moveTo(newFile);
}
And how to get submitted inputs:
Form(tuple("groupId" -> text, "tagId" -> text)).bindFromRequest.fold(
errors => ...,
params => ....
)
But how to combine them together?
I don't find a suitable type for file
can be used in Form(tuple(...))
, and neither a way to get input value in request.body
.
This answer is for Java, but you should be able to adapt it to Scala fairly easily.
What you need to do is define a Model for all the fields in your form except the file. Then use the file-upload API as normal to retrieve the file.
For example, this is what I did:
The Form (in upload.scala.html):
The Model (models/UploadResource.java):
The Controller (controllers/UploadResourceController.java):
I hope this helps.
An example in Scala where the form field is required:
Model:
Controller:
I was uploading a file using angular, with other form parameters. I created mine as below and it works.
Angular Function
Play 2.1 Controller
Another example how to do this can be this:
Model:
Controller
Dont forget to name the file, because you might end up wondering what went wrong.