我有以下域对象:
class Color {
String name
String fileLocation
static constraints = {
name (nullable: false, blank: false)
}
}
在我的 Controller 中,我正在执行以下操作:
def save() {
def colorInstance = new Color(params)
if (colorInstance.save(flush: true)) {
def file = request.getFile("myfile")
if (!file.empty && uploadService.isFileAllowed(file)) {
uploadService.uploadFile(file, file.originalName, "folderName")
}
}
else {
render (view: "create", model: [coorInstance: colorInstance])
}
}
一切正常,但是,我不确定在上传的文件超出允许范围时如何引发错误。即
uploadService.isFileAllowed(file)
返回false
?我该如何向用户说出错误
Uploaded file isn't allowed
当
uploadService.isFileAllowed(file)
返回false时?注意:
isFileAllowed
方法正在读取文件的前几个字节以确定文件的类型。
最佳答案
因此,如果isFileAllowed
返回false或文件为空,它将为colorInstance添加错误到fileLocation属性。仅在colorInstance成功验证后才会上传文件(以防止未保存的对象上传文件)。
附带说明,部分原因是,我更喜欢将文件保存在表中。它使验证变得不那么麻烦,并且不可能在对象和文件之间断开连接。 -我的2c。
def save() {
def colorInstance = new Color(params)
def file = request.getFile("myfile")
if (!file.empty && uploadService.isFileAllowed(file)) {
if (colorInstance.validate()) {
uploadService.uploadFile(file, file.originalName, "folderName")
}
}
else {
colorInstance.errors.rejectValue('fileLocation','error.message.code.here')
}
if (colorInstance.save(flush: true)) {
//do whatever here
}
else {
render (view: "create", model: [coorInstance: colorInstance])
}
}
关于validation - 如何在Grails中添加文件类型的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326610/