【问题标题】:Grails 3 Loading Static FilesGrails 3 加载静态文件
【发布时间】:2016-06-01 18:51:51
【问题描述】:

我在 Grails 3 应用程序的 assets 文件夹中有一些 PDF 文件。我想在用户单击某个按钮时加载它们。即用户单击“获取第一本书”按钮,grails 控制器会查找资产文件夹中的所有文件,直到找到匹配项,然后返回正确的文件。

目前,我通过直接访问路径来加载文件。即我正在使用明确的绝对路径。根据这个post,这是可取的方法之一。但是,我想通过要求我的应用程序获取资产文件夹中的所有资产而不是使用任何路径来在 grails 中加载文件。

然后我的问题是,是否有可能以简单的方式从资产文件夹中获取所有文件,就像我们可以在 yml 文件 (grailsApplication.config.someProperty) 中获取属性一样

【问题讨论】:

    标签: java grails groovy


    【解决方案1】:

    在这里找到解决方案:Grails : getting assets local storage path inside the controller

    以下示例:

    def assetResourceLocator
    
    assetResourceLocator.findAssetForURI('file.jpg')?.getInputStream()?.bytes
    

    对我来说效果很好。

    【讨论】:

      【解决方案2】:

      这段代码对我来说是类似的(但是,我的文件位于我的项目目录之外)。它是一个控制器方法,它接收文件名(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()
              }
          }
      

      【讨论】:

      • 抱歉,这不是真正要求的解决方案。但无论如何感谢您的关注。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      相关资源
      最近更新 更多