2013-03-10 23 views
0

我有以下的域對象:如何添加驗證文件類型的Grails

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方法首先讀取文件的幾個字節,以確定它是什麼類型的文件。

+0

真的取決於顏色和文件之間的關係。詳細解釋「uploadService.uploadFile」的做法 – 2013-03-10 20:02:02

+0

該方法將文件保存在文件夾中並返回保存文件的絕對路徑。該路徑保存在'fileLocation'屬性中 – birdy 2013-03-10 21:09:53

回答

0

所以,如果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]) 
    } 
} 
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" 
} 
+0

Flash Message是一個很好的建議。然而,爲了拋出錯誤而不知道Grails中的「flass message magic」,birdy可以簡單地使用包含錯誤的新模型渲染前一個視圖。這也可以 – 2013-03-11 03:44:02

1

將此登錄在你的控制器

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"); 
     } 
+0

這是問題標題的答案,但不是問題的答案。 – eugene82 2013-03-11 10:12:24