How to add validation for file type in grails

2019-08-26 13:32发布

I have a domain object with following:

class Color {
  String name
  String fileLocation

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

In my controller I'm doing the following:

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])
  }
}

This all works fine however, I'm not sure how to throw an error when the uploaded file isn't what is allowed. i.e. uploadService.isFileAllowed(file) returns false ??

How can I throw an error back to the user saying

Uploaded file isn't allowed

when uploadService.isFileAllowed(file) returns false ?

Note:

The isFileAllowed method is reading first few bytes of a file to determine what type of file it is.

3条回答
成全新的幸福
2楼-- · 2019-08-26 13:41

So if isFileAllowed returns false or the file is empty, it will add an error to the colorInstance to the fileLocation property. It will only upload the file if the colorInstance validates successfully (to prevent files uploaded for unsaved objects).

As a side note, I prefer saving files in tables partly for this reason. It makes validation much less clunky and its impossible to have a disconnect between your objects and the files. - Just my 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])
  }
}
查看更多
等我变得足够好
3楼-- · 2019-08-26 13:47

apply this login in your controller

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");
        }
查看更多
够拽才男人
4楼-- · 2019-08-26 13:58

What if you save an error message to flash memory and then render it on the page if it exists? 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"
}
查看更多
登录 后发表回答