validation - 如何在Grails中添加文件类型的验证

标签 validation grails file-upload groovy

我有以下域对象:

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/

相关文章:

validation - 接收,使用 CreateML 创建文本分类器模型时为 "An error was thrown and was not caught: The validation data provided must contain ..."

mysql - 为什么要在所需的数据库列上设置 `null: false, default: ""`?

url重写的Grails站点地图问题

grails - 如果索引大于 255,则数据绑定(bind)不起作用

javascript - 单击事件的多个答案

c# - 从 HTML 网页 (C#) 将文件上传到 Azure Blob?

javascript - 使用 vuejs 输入字段实时验证

javascript - 由于 JavaScript 验证,导入现有 Maven 项目后 Eclipse 构建工作区挂起

grails - 带有审核日志记录插件的Grails运行时异常

javascript - 如何读取.txt文件的第一行?