Lil*_*a 5 7 scala playframework-2.0
如何在使用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 _ ))
Run Code Online (Sandbox Code Playgroud)
有一个简单的方法来做到这一点?使用内置格式?
我认为您必须单独处理分段上传的文件组件,然后将其与表单数据结合起来.您可以通过多种方式执行此操作,具体取决于您希望治疗图像字段实际存在的位置(文件路径为a String,或者,将字面意思视为java.io.File对象).
对于最后一个选项,您可以将NewComplication案例类的处理图像字段设置为Option[java.io.File]并在表单映射中处理它ignored(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."))
}
Run Code Online (Sandbox Code Playgroud)
如果您只想存储文件路径,则会应用类似的操作.
有几种方法可以处理文件上传,这通常取决于你在文件服务器端做什么,所以我认为这种方法是有道理的.