Scala Play download file in form

How to upload a file in the form defined using the Scala Play play.api.data.Forms framework. I want the file to be stored in Image Image.

  val cForm: Form[NewComplication] = Form( mapping( "Name of Vital Sign:" -> of(Formats.longFormat), "Complication Name:" -> text, "Definition:" -> text, "Reason:" -> text, "Treatment:" -> text, "Treatment Image:" -> /*THIS IS WHERE I WANT THE FILE*/, "Notes:" -> text, "Weblinks:" -> text, "Upper or Lower Bound:" -> text) (NewComplication.apply _ )(NewComplication.unapply _ )) 

Is there an easy way to do this? Using inline formats?

+7
source share
1 answer

I think that you will have to process the component of the multi-page download file separately and subsequently combine it with the form data. You could do this in several ways, depending on what you want the processing field to actually be (the path to the file as String , or to take you literally as a java.io.File object.)

For this last option, you can make the processing image field of your class NewComplication case Option[java.io.File] and process it in your view using ignored(Option.empty[java.io.File]) (therefore it will not be associated with other data.) Then in your action do something like this:

 def createPost = Action(parse.multipartFormData) { implicit request => request.body.file("treatment_image").map { picture => // retrieve the image and put it where you want... val imageFile = new java.io.File("myFileName") picture.ref.moveTo(imageFile) // handle the other form data cForm.bindFromRequest.fold( errForm => BadRequest("Ooops"), complication => { // Combine the file and form data... val withPicture = complication.copy(image = Some(imageFile)) // Do something with result... Redirect("/whereever").flashing("success" -> "hooray") } ) }.getOrElse(BadRequest("Missing picture.")) } 

A similar thing applies if you just want to save the file path.

There are several ways to handle file uploads , which usually depend on what you do with the files on the server side, so I think this approach makes sense.

+9
source share

All Articles