如何在使用Scala Play的play.api.data.Forms
框架定义的表单中上传文件。我希望文件存储在Treatment 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 _ ))
有一种简单的方法吗?使用内置格式?
答案 0 :(得分:9)
我认为您必须单独处理分段上传的文件组件,然后将其与表单数据结合起来。您可以通过多种方式执行此操作,具体取决于您希望治疗图像字段实际存在的位置(文件路径为String
,或者将字面意思视为java.io.File
对象。)< / p>
对于最后一个选项,您可以将NewComplication
案例类的处理图片字段设为Option[java.io.File]
,并在表单映射中使用ignored(Option.empty[java.io.File])
处理它(因此它赢了&#39;与其他数据绑定。)然后在你的行动中做这样的事情:
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."))
}
如果您只想存储文件路径,则会应用类似的操作。
handle file upload有几种方法通常取决于你在文件服务器方面做了什么,所以我觉得这种方法很有意义。