grails - 如何获取Grails应用程序的绝对路径

标签 grails

我希望用户能够下载我的 web-app/images 文件夹中的文件

我构建了一个这样的 Action :

def download () {
    def file = new File (params.filepath)

    if (file.exists()) {
        response.setContentType("application/octet-stream")
        response.setHeader("Content-disposition", "filename=${file.name}")
        response.outputStream << file.bytes
        return
    }
}

但是,当我传入文件路径 /images/myimage.jpeg 时,它找不到该图像。

问题

如何获取部署 grails 应用程序的绝对路径,以便我可以将代码更改为:

def file = new File (absolutePath + params.filepath)

注意

System.properties['base.dir'] 在本地工作,但在部署到 tomcat 时不工作。

最佳答案

这将在本地和部署的 war 中起作用:

class MyController implements org.springframework.context.ResourceLoaderAware {
  ResourceLoader resourceLoader 
  def download() {
    //org.springframework.core.io.Resource
    def someImage = resourceLoader.getResource("/images/someImage.png").getFile()
  }
}

mail user thread 中找到它.

关于grails - 如何获取Grails应用程序的绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16225657/

相关文章:

Java HttpServletResponse 带有空白值 header ?

grails - 将 Grails 项目用于公共(public)代码和对其他 Grails 项目的依赖

java - 保存对象时出错 : No Hibernate Session bound

grails - r:img导致资源未定位

grails - grails 2.x中具有可加性标志的log4j dsl

mysql - 如何在 GORM 表架构更改后让系统正常工作?

服务层中的验证和验证错误

html - DIV 突破 P 标签

grails - 在 Grails 应用程序中使用 Gradle 包装器生成 WAR

grails - 在 Spring Security 中自定义身份验证