我想从部署 grails 应用程序的同一服务器的外部文件夹加载图像。假设在 Linux - 用户主页中。
我在网上找到了很多文章,但没有成功。
我的.gsp
代码是尝试:
<asset:image src="libs/test/1.jpg" alt=""/>
<asset:image src="images/2.jpg" alt=""/>
<img src="${asset.assetPath(src: '13123.jpg')}" />
<img src="\home\user\img\Desert.jpg" />
我需要类似的东西:
<img src="${userhome}/image.jpg" />
其中 userhome 是预定义的文件夹。
使用 Assets 管道插件的另一个问题我收到此错误:
Byte array resource [resource loaded from byte array] cannot be resolved to URL
最佳答案
您不能使用asset标签指向外部文件。但是您可以从文件系统检索文件并将其作为字节数组“附加”到响应,这是 Controller 操作的示例:
def getImage() {
byte[] imageInBytes = imageService.getImage()
response.with{
setHeader('Content-length', imageInBytes.length.toString())
contentType = 'image/jpg' // or the appropriate image content type
outputStream << imageInBytes
outputStream.flush()
}
}
服务逻辑可能如下所示:
byte[] getImage() {
ByteArrayOutputStream baos = new ByteArrayOutputStream()
ImageIO.write(ImageIO.read(new File('/path/to/file')), "jpg", baos)
baos.toByteArray()
}
最后是 gsp 上的 img 标签:
<img ... src="${createLink(controller: 'imageController', action: 'getImage')}" />
您可能想要使用 id 和 URL 映射来通过服务逻辑检索特定图像。
关于java - grails 3加载图像外部文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42212057/