【问题标题】:Grails unable to find pdf resources when deploying war部署战争时Grails无法找到pdf资源
【发布时间】:2013-09-24 10:18:17
【问题描述】:

我正在控制器中编写一个动作来从 webapp 目录下载 pdf。当我使用 run-app 命令运行应用程序时,它工作得非常好。但是当我创建一个战争时,它会抛出在浏览器上找不到文件的错误。我的代码如下。

 def pdfDownlod ={
      def pdfFileName=params.pdfFileName
      def pdfFile = new File('web-app/sales/resources/pdf/'+pdfFileName)
      response.setContentType("application/pdf")
      response.setHeader("Content-disposition", "attachment; filename=${pdfFileName}")
      response.outputStream << pdfFile?.getBytes()
      response.outputStream.flush()
      return
  }

请告诉我问题的根本原因和解决方案。

提前致谢。

【问题讨论】:

    标签: file grails web-applications path


    【解决方案1】:

    那是因为在您部署的战争中,web-app 文件夹不存在。要在 dev 和 prod 中正确获取资源,请使用 grailsResourceLocator bean。

    例子:

    class MyController {
    
    def grailsResourceLocator
    
      def pdfDownlod ={
          def pdfFileName = params.pdfFileName
          final Resource pdfFile = grailsResourceLocator.findResourceForURI('web-app/sales/resources/pdf/'+pdfFileName)
    
          response.setContentType("application/pdf")
          response.setHeader("Content-disposition", "attachment; filename=${pdfFileName}")
          response.outputStream << pdfFile?.file.bytes // << already flushes!
          return
      }
    }
    

    【讨论】:

    • 感谢您的快速回复。如果在战争中,wep-app 不存在,那么它从哪里获取所有图像、css 和 js?
    【解决方案2】:

    你可以试试这个语法,它会很适合你。

    def pdfFile = new File(ServletContextHolder.servletContext.getRealPath('sales/resources/pdf/'+pdfFileName))
    

    享受吧。

    【讨论】:

    • 感谢回答的朋友。你能告诉我为什么我的代码不工作吗?
    • 当我们创建war文件时,web-app的所有文件夹直接放在你的foo文件夹中,你的war文件名为foo.war。我的解决方案对你有用吗?
    猜你喜欢
    • 2015-01-26
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多