如何包括在斯卡拉玩!2形式的图片类型?(How to include a picture type

2019-09-19 07:53发布

根据该指南 ,可通过手写HTML表单上传文件。 我想处理文件上传作为一个更大的形式包括文本字段(例如姓名和电子邮件)的一部分。 以下是我不得不远(相当难看):

def newUser = Action(parse.multipartFormData) { implicit request =>{   
    //handle file
    import play.api.mvc.MultipartFormData.FilePart
    import play.api.libs.Files.TemporaryFile

    var uploadSuccessful = true 
    var localPicture: FilePart[TemporaryFile] = null

    request.body.file("picture").map { picture =>
    localPicture = picture   }.getOrElse {
    uploadSuccessful = false   }

    //process the rest of the form
    signupForm.bindFromRequest.fold(
      errors => BadRequest(views.html.signup(errors)),
      label => {
        //file uploading code here(see guide), including error checking for the file.

        if(uploadSuccesful){
        User.create(label._1, label._2, label._3._1, 0, "NO PHOTO", label._4)
        Redirect(routes.Application.homepage).withSession("email" -> label._2)
        } else {
        Redirect(routes.Application.index).flashing(
        "error" -> "Missing file"
        }
      })
     }   }

这看起来巨丑我。 请注意,我已经定义了一个signupForm的地方,包括所有领域(除了文件上传照片)。 我的问题是:有没有的要对此更漂亮呢? 也许通过在signupForm文件字段,然后处理错误均匀。

Answer 1:

到目前为止,我认为这是不可能的二进制数据直接绑定到一个表单,您只能绑定引用(如图片的ID或名称)。 然而,你可能会重新制定你的代码位:

def newUser() = Action(parse.multipartFormData) { implicit request => 
  import play.api.mvc.MultipartFormData.FilePart
  import play.api.libs.Files.TemporaryFile

  request.body.file("picture").map { picture =>
    signupForm.bindFromRequest.fold(
      errors => BadRequest(views.html.signup(errors)),
      label => {
        User.create(label._1, label._2, label._3._1, 0, picture.absolutePath(), label._4)
        Redirect(routes.Application.homepage).withSession("email" -> label._2)
      }
    )
  }.getOrElse(Redirect(routes.Application.index).flashing("error" -> "Missing file"))
}


Answer 2:

您可以使用asFormUlrEncoded ,如下图所示:

def upload = Action(parse.multipartFormData) { request =>
  val formField1 = request.body.asFormUrlEncoded("formField1").head;
  val someOtherField = request.body.asFormUrlEncoded("someOtherField").head;
  request.body.file("photo").map { picture =>
    ...
  }
}


文章来源: How to include a picture type in a form in Play!2 in Scala?