在 GSP (Grails) 中显示图像,从数据库获取链接

发布于 2024-10-03 17:00:24 字数 632 浏览 3 评论 0原文

我是 Grails 新手。我试图显示网站中每个产品的图像缩略图,如下所示:

<a href="#"><img src="${resource(dir:"images", file: "Nikon.jpg") }"/></a>/* 1 */

这里的问题是我想将图像链接保存在数据库中,并通过以下方式获取链接:

${fieldValue(bean: productInstance, field: "image")}  /* 2 */

但是我无法将 /* 2 / 代码替换为 / 1 */ 中“Nikon.jpg”的位置,会导致语法错误!

经过一些研究后,我发现大多数教程都展示了如何显示直接存储在数据库中的图像(例如, 如何在 grails GSP 中显示图像?)。我不确定这种方法是否更好,但我仍然想从数据库中获取图像链接。

我还尝试搜索 grails 标签库以查找任何支持标签,但没有成功。谁能给我提示吗?

I'm a Grails newbie. I'm trying to show an images thumbnail for every product in a site, like this:

<a href="#"><img src="${resource(dir:"images", file: "Nikon.jpg") }"/></a>/* 1 */

The problem here is that I want to save the image link in the database, and get the link by:

${fieldValue(bean: productInstance, field: "image")}  /* 2 */

But I can't replace the /* 2 / code into the places of "Nikon.jpg" in / 1 */, it causes syntax error!

After doing some research, I see that most tutorials show how to display image that stores directly in database (for example, How to display image in grails GSP?). I'm not sure if that approach is better, but I still want to take image link from database.

I also tried to search grails tag library to find any support tag, but with no success. Can anyone give me a hint?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

疾风者 2024-10-10 17:00:25

等一下......如果我从字面上读你的问题,你正在尝试这样的事情:

<a href="#"><img src="${resource(dir:"images", 
        file: "${fieldValue(bean: productInstance, field: "image")} ") }"/></a>

嗯,这是令人费解和错误的。这应该有效:

<a href="#"><img src="${fieldValue(bean: productInstance, field: "image")}"/></a>

Wait a sec... If I read your question literally, you're trying something like this:

<a href="#"><img src="${resource(dir:"images", 
        file: "${fieldValue(bean: productInstance, field: "image")} ") }"/></a>

Well, that's convoluted and wrong. This should work:

<a href="#"><img src="${fieldValue(bean: productInstance, field: "image")}"/></a>
小霸王臭丫头 2024-10-10 17:00:25

我将图像存储路径保存在数据库中,例如 ../../../web-
使用 FileUploadService 的 app/personImages/imageName.img
扩展。
用于在 GSP 中显示图像

<img style="height:120px;width:102px;"src="${resource(dir:'personImages',file:domainInstance.id + '.png')}" />

示例

首先使用 FileUploadSevices 文件

域:

class PersonalDetails {

String avatar

static constraints = {

    avatar(nullable:true,maxSize: 1024000)

}

控制器 save() 操作:

// Save Avatar if uploaded
def avatarImage = request.getFile('avatar')
    if (!avatarImage.isEmpty()) {
    personalDetailsInstance.avatar = fileUploadService.uploadFile(avatarImage, 
       "${personalDetailsInstance.id}.png", "personImages")
        }

DB 文件存储路径:

在头像文件中:

C:\Documents and Settings\Administrator\Documents\workspace-ggts-3.4.0.RELEASE\IDiary\web-app\personImages/1.png

列出 GSP:

<img style="height: 120px;width: 102px;"src="${resource(dir:'personImages', file: personalDetailsInstance.id + '.png')}" />

I save the image storagePath in Database like ../../../web-
app/personImages/imageName.img
extension using FileUploadService.
For displaying images in GSP

<img style="height:120px;width:102px;"src="${resource(dir:'personImages',file:domainInstance.id + '.png')}" />

Example

First Use FileUploadSevices file

Domain:

class PersonalDetails {

String avatar

static constraints = {

    avatar(nullable:true,maxSize: 1024000)

}

Controller save() action:

// Save Avatar if uploaded
def avatarImage = request.getFile('avatar')
    if (!avatarImage.isEmpty()) {
    personalDetailsInstance.avatar = fileUploadService.uploadFile(avatarImage, 
       "${personalDetailsInstance.id}.png", "personImages")
        }

DB file storage path:

In avatar file :

C:\Documents and Settings\Administrator\Documents\workspace-ggts-3.4.0.RELEASE\IDiary\web-app\personImages/1.png

List GSP:

<img style="height: 120px;width: 102px;"src="${resource(dir:'personImages', file: personalDetailsInstance.id + '.png')}" />
笑着哭最痛 2024-10-10 17:00:25

我需要一个由 http://grails 组合而成的安全解决方案.asia/grails-example-application-simple-document-management-systemhttp://grails.asia/grails-render-images-on-the-fly-in-gsp 。为此,我使用了一个存储图像路径的域、一个显示图像的 gsp 和一个为图像提供服务的控制器

域:

class Document {
String filename
String fullPath
Date uploadDate = new Date()
static constraints = {
    filename(blank:false,nullable:false)
    fullPath(blank:false,nullable:false)
}

}

Grails 服务器页面:

<!DOCTYPE html>
<html>
    <head>
        <meta name="layout" content="main">
        <title>Document List</title>
    </head>
<body>

        <div class="content scaffold-list" role="main">
            <h1>Document List</h1>
        <g:if test="${flash.message}"><div class="message" role="status">${flash.message}</div></g:if>
            <table>
                <thead>
                    <tr>
                    <g:sortableColumn property="filename" title="Filename" />
                    <g:sortableColumn property="uploadDate" title="Upload Date" />
                    <g:sortableColumn property="Preview" title="Vista Previa" />
                </tr>
            </thead>
            <tbody>
                <g:each in="${documentInstanceList}" status="i" var="documentInstance">
                    <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
                        <td><g:link action="download" id="${documentInstance.id}">${documentInstance.filename}</g:link></td>
                        <td><g:formatDate date="${documentInstance.uploadDate}" /></td>
                        <td><g:img style="height:120px;width:120px;" uri="/doclist/images?id=${documentInstance.id}"  /></td>
                    </tr>
                </g:each>
            </tbody>
        </table>

        <div class="pagination">
            <g:paginate total="${documentInstanceTotal}" />
        </div>
    </div>
</body>
</html>

< strong>控制器:

import org.springframework.security.access.annotation.Secured
class DoclistController {

@Secured(['ROLE_ADMIN'])      
def list(){

    params.max = 10
    [documentInstanceList: Document.list(params), documentInstanceTotal: Document.count()]

    //render view: 'list'
}

@Secured(['ROLE_ADMIN'])      
def images(long id){
    Document documentInstance = Document.get(id)
    if ( documentInstance == null) {
        flash.message = "Document not found."
        redirect (action:'list')
    } else {

        def file = new File(documentInstance.fullPath)
        def fileInputStream = new FileInputStream(file)
        def outputStream = response.getOutputStream()
        byte[] buffer = new byte[4096];
        int len;
        while ((len = fileInputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.flush()
        outputStream.close()
        fileInputStream.close()
    }
}
}

我显示数据库的图像如下

DoclistController 结果

希望这有帮助

I needed a secured solution that was made in combination of http://grails.asia/grails-example-application-simple-document-management-system and http://grails.asia/grails-render-images-on-the-fly-in-gsp . For that purpouse i used a Domain where i store the path of images, a gsp to show the images and a Controller to serve the images

Domain:

class Document {
String filename
String fullPath
Date uploadDate = new Date()
static constraints = {
    filename(blank:false,nullable:false)
    fullPath(blank:false,nullable:false)
}

}

Grails Server Page:

<!DOCTYPE html>
<html>
    <head>
        <meta name="layout" content="main">
        <title>Document List</title>
    </head>
<body>

        <div class="content scaffold-list" role="main">
            <h1>Document List</h1>
        <g:if test="${flash.message}"><div class="message" role="status">${flash.message}</div></g:if>
            <table>
                <thead>
                    <tr>
                    <g:sortableColumn property="filename" title="Filename" />
                    <g:sortableColumn property="uploadDate" title="Upload Date" />
                    <g:sortableColumn property="Preview" title="Vista Previa" />
                </tr>
            </thead>
            <tbody>
                <g:each in="${documentInstanceList}" status="i" var="documentInstance">
                    <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
                        <td><g:link action="download" id="${documentInstance.id}">${documentInstance.filename}</g:link></td>
                        <td><g:formatDate date="${documentInstance.uploadDate}" /></td>
                        <td><g:img style="height:120px;width:120px;" uri="/doclist/images?id=${documentInstance.id}"  /></td>
                    </tr>
                </g:each>
            </tbody>
        </table>

        <div class="pagination">
            <g:paginate total="${documentInstanceTotal}" />
        </div>
    </div>
</body>
</html>

Controller:

import org.springframework.security.access.annotation.Secured
class DoclistController {

@Secured(['ROLE_ADMIN'])      
def list(){

    params.max = 10
    [documentInstanceList: Document.list(params), documentInstanceTotal: Document.count()]

    //render view: 'list'
}

@Secured(['ROLE_ADMIN'])      
def images(long id){
    Document documentInstance = Document.get(id)
    if ( documentInstance == null) {
        flash.message = "Document not found."
        redirect (action:'list')
    } else {

        def file = new File(documentInstance.fullPath)
        def fileInputStream = new FileInputStream(file)
        def outputStream = response.getOutputStream()
        byte[] buffer = new byte[4096];
        int len;
        while ((len = fileInputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.flush()
        outputStream.close()
        fileInputStream.close()
    }
}
}

I show the images of database as follows

DoclistController Result

Hope this helps

口干舌燥 2024-10-10 17:00:24

避免语法错误的正确语法是:

但我建议您编写自己的 tagLib,因为编写一个 tagLib 确实非常简单,而且如果您要经常使用此代码,您的 GSP 看起来会更好。您可以轻松编写一个名为以下内​​容的标签:
并且为了获得额外的可用性,您也可以使 tagLib 输出链接。

在我看来,编写 tagLibs 的简单性确实是 grails 最好的特性之一。

The proper syntax to avoid a syntax errors would be:

<img src="${resource(dir:'images', file:fieldValue(bean:productInstance, field:'image'))}" />

But I recommend you write your own tagLib, because it is really very simple to write one and your GSPs will look much nicer if you are going to use this code a lot. You could easily write a tag that would be called something like:
<product:image product='productInstance' /> and for extra usability you could make the tagLib output the link as well.

The simplicity of writing tagLibs is really one of the best grails features in my opinion.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文