表单中的Scala播放上载文件

表单中的Scala播放上载文件,scala,playframework-2.0,Scala,Playframework 2.0,如何在Scala Play的Play.api.data.Formsframework定义的表单中上载文件。我希望该文件存储在处理图像下 val cForm: Form[NewComplication] = Form( mapping( "Name of Vital Sign:" -> of(Formats.longFormat), "Complication Name:" -> text, "Definition:" -> tex

如何在Scala Play的
Play.api.data.Forms
framework定义的表单中上载文件。我希望该文件存储在处理图像下

  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 _ ))  

有没有一个简单的方法可以做到这一点?通过使用内置格式?

我认为您必须单独处理多部分上载的文件组件,然后将其与表单数据合并。根据您希望治疗图像字段实际是什么(文件路径为
字符串
,或者确切地说是
java.io.file
对象),您可以通过几种方式来实现这一点

对于最后一个选项,您可以将
newcommplication
案例类的治疗图像字段设置为
选项[java.io.File]
,并在表单映射中使用
忽略(option.empty[java.io.File])
(这样它就不会与其他数据绑定)。然后在您的操作中执行以下操作:

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."))
}
如果只想存储文件路径,也可以使用类似的方法

有几种方法通常取决于您在服务器端对文件所做的操作,因此我认为这种方法是有意义的