【问题标题】:How to add validation for file type in grails如何在 grails 中添加对文件类型的验证
【发布时间】:2013-03-11 20:07:45
【问题描述】:

我有一个包含以下内容的域对象:

class Color {
  String name
  String fileLocation

  static constraints = {
    name (nullable: false, blank: false)
  }
}

在我的控制器中,我正在执行以下操作:

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 ??

我怎样才能将错误返回给用户说

不允许上传文件

uploadService.isFileAllowed(file) 何时返回 false ?

注意:

isFileAllowed 方法是读取文件的前几个字节以确定它是什么类型的文件。

【问题讨论】:

  • 真的要看Color和文件的关系。详细解释uploadService.uploadFile做了什么
  • 该方法将文件保存在文件夹中并返回保存文件的绝对路径。该路径保存在fileLocation 属性中

标签: validation grails file-upload groovy


【解决方案1】:

如果您将错误消息保存到闪存中,然后在页面上呈现它(如果存在)会怎样? See this post for help.

if (!file.empty && uploadService.isFileAllowed(file)) {
  uploadService.uploadFile(file, file.originalName, "folderName")
} else {
    flash.error = "Uploaded file isn't allowed"
}

【讨论】:

  • Flash Message 是一个很好的推荐。然而,要在不了解 Grails 中的“flass message magic”的情况下将错误返回,birdy 可以简单地使用包含错误的新模型渲染先前的视图。也可以
【解决方案2】:

在您的控制器中应用此登录

String fileName = "something.ext";
        int a = fileName.lastIndexOf(".");
        String extName = fileName.substring(a);
        System.out.println(fileName.substring(a));
        ArrayList<String> extList = new ArrayList<String>();
        extList.add("jpg");
        extList.add("jpeg");
        extList.add("png");
        if(extList.contains(extName))
        {
            System.out.println("proceed");
        }
        else{
            System.out.println("throw exception");
        }

【讨论】:

  • 这是问题标题的答案,但不是问题的答案。
【解决方案3】:

所以如果isFileAllowed返回false或者文件为空,就会给fileLocation属性添加colorInstance的错误。仅当 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])
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 2021-01-08
    • 2010-09-09
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多