Grails: - 如何在文件系统中显示图像

时间:2010-09-03 11:14:45

标签: image grails

我需要在grails的项目目录中显示文件系统中的图像。 我用了

< img src="${createLinkTo(dir: '/Users/ME/ddImages/reg/', file: '${userInstance.fileName}.jpg')}" alt="User Photo"/>

但这似乎不起作用

所以有什么帮助?

2 个答案:

答案 0 :(得分:2)

BTW,grails标签被删除,使用资源;并且该标记将使您保持在应用程序的基本路径中

http://www.grails.org/Tag+-+createLinkTo

img标签上的文档 http://www.w3schools.com/tags/att_img_src.asp

“src”的可能值

An absolute URL - points to another web site (like src="http://www.example.com/image.gif")
A relative URL - points to a file within a web site (like src="image.gif")

答案 1 :(得分:0)

认为您正在尝试呈现不在项目的webroot中的文件。您只需将URL传递给视图就可以做到这一点。 您可以这样做的一种方法是将图像文件作为流读取,然后将字节流写入视图。 e.g:

<img src="${request.contextPath}/controllerName/getImage?filepath=${path_to_file_in_filesystem}" alt="whatever. alternatively, filename"/>

然后控制器中的动作将如下所示:

def getImage(){
    def path = params.filepath
    //returns an image to display
    BufferedImage originalImage = ImageIO.read(new File(path));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    def fileext = path.substring(path.indexOf(".")+1, path.length())

    ImageIO.write( originalImage, fileext, baos );
    baos.flush();

    byte[] img = baos.toByteArray();
    baos.close();
    response.setHeader('Content-length', img.length.toString())
    response.contentType = "image/"+fileext // or the appropriate image content type
    response.outputStream << img
    response.outputStream.flush()
}

应该这样做。希望这有助于某人。

相关问题