如何在Scala的Play!2中将图片类型包含在表单中? [英] How to include a picture type in a form in Play!2 in Scala?
问题描述
根据本指南,人们可以通过编写html表单来上传文件用手.我想将文件上传作为包含文本字段(例如名称和电子邮件)的较大表单的一部分来处理.这是我必须做的(非常难看):
According to this guide, one can upload files by writing the html form by hand. I want to handle file upload as part of a bigger form that includes text fields (for example name and email). Here is what I have to far (quite ugly):
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中包含file字段,然后统一处理错误.
This looks tremendously ugly to me. Note that I have defined a signupForm somewhere that includes all fields (apart from the file upload one). My question is: Is there a prettier way of going about this? Perhaps by including the file field in the signupForm and then handling errors uniformly.
推荐答案
到目前为止,我认为无法将二进制数据直接绑定到表单,只能绑定引用(例如图片的ID或名称).不过,您可以重新编写一下代码:
So far I think it's not possible to bind binary data to a form directly, you can only bind the reference (e.g. the picture's ID or name). You could however reformulate your code a bit:
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"))
}
这篇关于如何在Scala的Play!2中将图片类型包含在表单中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!