Grails 3 - get asset path in service

别说谁变了你拦得住时间么 提交于 2019-12-12 03:27:00

问题


I need to get the path of a static resource located in assets/schemas/resource.json in a Grails 3 service.

At the moment it is defined as

private final String SCHEMA = 'grails-app/assets/schemas/resource.json',

which is fine for development environment, but of course not for production (as it would be located in <app_root>/assets/resource.json.

I tried to search how to exploit the Asset Pipeline in my case, but up to now I really have no idea :P

Thanks in advance!


回答1:


It is covered in the docs. http://bertramdev.github.io/grails-asset-pipeline/guide/usage.html

In a controller or service, inject the assetResourceLocator and use assetResourceLocator.findAssetForURI()




回答2:


It works locally but not when deployed to a server. Using Grails 3.1.0, Java 1.8.0_91 and Tomcat 8.0.33.

assetResourceLocator?.findAssetForURI('myFolder/placeholder.jpg')?.byteArray

returns

groovy.lang.MissingPropertyException: No such property: byteArray for class: org.springframework.web.context.support.ServletContextResource

EDIT: Solved it:

assetResourceLocator?.findAssetForURI('myFolder/placeholder.jpg')?.getInputStream()?.bytes



回答3:


Complete example:

class ExampleService {
  def assetResourceLocator

  def someMethod() {
    Resource res = assetResourceLocator.findAssetForURI('test.css')
    String url = res.getURL()
    String uri = res.getURI()
  }
}

Source: http://bertramdev.github.io/grails-asset-pipeline/guide/usage.html



来源:https://stackoverflow.com/questions/36457869/grails-3-get-asset-path-in-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!