表单中的Scala Play上传文件 [英] Scala Play upload file within a form

查看:102
本文介绍了表单中的Scala Play上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在Scala Play的play.api.data.Forms框架定义的表单中上传文件.我希望将文件存储在处理图像"下.

How would I upload a file within a form defined with Scala Play's play.api.data.Forms framework. I want the file to be stored under 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 _ ))  

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

is there a simple way to do this? By using built in Formats?

推荐答案

我认为您必须分别处理分段上传的文件组件,然后再将其与表单数据合并.您可以通过几种方法来完成此操作,具体取决于您希望治疗图像字段实际是什么(文件路径为String,或者从字面意义上讲,为java.io.File对象.)

I think you have to handle the file component of a multipart upload separately and combine it with your form data afterwards. You could do this several ways, depending on what you want the treatment image field to actually be (the file-path as a String, or, to take you literally, as a java.io.File object.)

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

For that last option, you could make the treatment image field of your NewComplication case class an Option[java.io.File] and handle it in your form mapping with ignored(Option.empty[java.io.File]) (so it won't be bound with the 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 would apply if you wanted just to store the file path.

有几种方法处理文件上传,这通常取决于什么您正在服务器端处理文件,所以我认为这种方法很有意义.

There are several ways to handle file upload which will usually depend on what you're doing with the files server-side, so I think this approach makes sense.

这篇关于表单中的Scala Play上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆