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