如何在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"))
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 以2位数年份输入时,Bootstrap Datepicker默认为1900
- shell编程:命令替换的运用
- Scala将单词保留为JSON字段名称,带有Json.writes [A](等效于
- 淘宝(taobao)HSF框架
- vim – 在命令模式下向前/向后移动一个单词?
- “-bash:gcc:command not found”在编译c时使用cygwin?
- 在Angular 2中,通过ComponentFactory创建Component似乎没有
- angularjs – $dirty vs $invalid:有什么区别?
- AngularJS2 学习笔记——JavaScript
- 在AngularJS指令中加载来自templateURL的html(在django应用
