0

次のドメインオブジェクトがあります。

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方法では、ファイルの最初の数バイトを読み取って、ファイルの種類を判別します。

4

3 に答える 3

1

エラーメッセージをフラッシュメモリに保存し、存在する場合はページにレンダリングするとどうなりますか? ヘルプについては、この投稿を参照してください

if (!file.empty && uploadService.isFileAllowed(file)) {
  uploadService.uploadFile(file, file.originalName, "folderName")
} else {
    flash.error = "Uploaded file isn't allowed"
}
于 2013-03-10T22:16:26.653 に答える
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");
        }
于 2013-03-11T06:50:11.890 に答える
0

したがって、isFileAllowedfalse を返すか、ファイルが空の場合、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])
  }
}
于 2013-03-11T12:07:45.287 に答える