2016-06-01 9 views
3

Grails 3アプリケーションのassetsフォルダにいくつかのPDFファイルがあります。ユーザーがボタンをクリックしたときにロードしたいすなわち、ユーザーが「First book」ボタンをクリックすると、grailsコントローラは、アセットフォルダ内のすべてのファイルを検索し、一致するファイルを検索します。Grails 3静的ファイルの読み込み

現在、パスに直接アクセスしてファイルをロードしています。つまり、明示的なアボスルートパスを使用しています。このpostによれば、これはお勧めのアプローチの1つです。しかし、パスを使用するのではなく、アセットフォルダ内のすべてのアセットを取得するようにアプリケーションに依頼して、grailsでファイルをロードします。

私の質問は、その後、我々はYMLファイルのプロパティを取得することができますように簡単な方法で資産フォルダからすべてのファイルを取得することも可能である(grailsApplication.config.someProperty)

答えて

0

このコードは、のために似た何かを作ります私(ただし、私のファイルは私のプロジェクトディレクトリの外にあります)。そのコントローラメソッドは、ファイル名(id)とファイルタイプ(filetype)を受け取り、あらかじめ定義されたディレクトリを探します。私はあなたの "serverLocation"と "contentLocation"を適合させる必要があると思います。ファイル配信する

List listOfNewsletters = [] 

String contentLocation = grailsApplication.config.managedNewsletter.contentLocation; 

File rootDirectory = new File(servletContext.getRealPath("/")); 
File webappsDirectory = rootDirectory.getParentFile(); 
String serverLocation = webappsDirectory.getAbsolutePath(); 

serverLocation = serverLocation + contentLocation + "/"; 

File f = new File(serverLocation); 

if (f.exists()) { 
    f.eachFile() { File file -> 
     listOfNewsletters.push([ 
       path: file.path, 
       filename: file.name, 
       filetype: "pdf" 
     ]) 
    } 
} 

:ビューに渡すことができるファイルのリストを取得するには

def openNewsletter() { 
     if (params.id != null && params.filetype != null) { 

      String pdf = (String) params.id + "." + (String) params.filetype;  

      String contentLocation = grailsApplication.config.managedNewsletter.contentLocation; 

      File rootDirectory = new File(servletContext.getRealPath("/")); 
      File webappsDirectory = rootDirectory.getParentFile(); 
      String serverLocation = webappsDirectory.getAbsolutePath();   

      serverLocation = serverLocation + contentLocation + "/"; 

      File pdfFile =new File(serverLocation + pdf); 

      response.contentType = 'application/pdf' // or whatever content type your resources are 
      response.outputStream << pdfFile.getBytes() 
      response.outputStream.flush() 
     } 
    } 
+0

申し訳ありませんが、実際には要求された解決策ではありません。しかし、とにかくあなたの注意に感謝します。 –

関連する問題