加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Scala中的Play!2中的表单中包含图片类型?

发布时间:2020-12-16 19:24:39 所属栏目:安全 来源:网络整理
导读:根据 this guide,可以通过手工编写html表单来上传文件.我想处理文件上传作为包含文本字段(例如名称和电子邮件)的更大表单的一部分.这就是我所要做的(非常难看): def newUser = Action(parse.multipartFormData) { implicit request ={ //handle file import
根据 this guide,可以通过手工编写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,"NO PHOTO",label._4)
        Redirect(routes.Application.homepage).withSession("email" -> label._2)
        } else {
        Redirect(routes.Application.index).flashing(
        "error" -> "Missing file"
        }
      })
     }   }

这看起来非常难看.请注意,我已经在某处定义了一个包含所有字段的signupForm(除了文件上传之外).我的问题是:有更好的方式来解决这个问题吗?也许通过在signupForm中包含文件字段然后统一处理错误.

解决方法

到目前为止,我认为不可能直接将二进制数据绑定到表单,您只能绑定引用(例如图片的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,picture.absolutePath(),label._4)
        Redirect(routes.Application.homepage).withSession("email" -> label._2)
      }
    )
  }.getOrElse(Redirect(routes.Application.index).flashing("error" -> "Missing file"))
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读