2012-07-11 53 views
4

根據this guide,可以通過手寫html表單來上傳文件。我想將文件上傳作爲包含文本字段(例如姓名和電子郵件)的更大表單的一部分。這是我所到之處(相當醜陋):如何在Play!2中的Scala中包含圖片類型?

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中包含文件字段,然後統一處理錯誤。

回答

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")) 
} 
0

可以使用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 => 
    ... 
    } 
} 
相關問題