2013-04-25 57 views
3

我希望用戶能夠下載一個文件在我的文件夾web-app/images如何獲得絕對路徑Grails應用

我已經建立了一個動作是這樣的:

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時不能工作。

回答

3

這將在本地和部署戰爭工作:

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發現了它。

+0

我得到resourceLoader爲空.. :( – 2015-11-10 09:07:57

1

def abolutePath = request.getSession().getServletContext().getRealPath("/images/myimage.jpeg")