【问题标题】:Displaying image in GSP (Grails), get link from database在 GSP (Grails) 中显示图像,从数据库中获取链接
【发布时间】:2011-05-13 17:01:30
【问题描述】:

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

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

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

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

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

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

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

【问题讨论】:

    标签: gsp grails


    【解决方案1】:

    我需要一个结合了 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>
    

    控制器:

    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()
        }
    }
    }
    

    我将数据库的图像显示如下

    希望对你有帮助

    【讨论】:

      【解决方案2】:

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

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

      例子

      首先使用 FileUploadServices 文件

      域:

      class PersonalDetails {
      
      String avatar
      
      static constraints = {
      
          avatar(nullable:true,maxSize: 1024000)
      
      }
      

      控制器保存()动作:

      // 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
      

      列出普惠制:

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

      【讨论】:

        【解决方案3】:

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

        &lt;img src="${resource(dir:'images', file:fieldValue(bean:productInstance, field:'image'))}" /&gt;

        但我建议您编写自己的 tagLib,因为编写一个非常简单,如果您要经常使用此代码,您的 GSP 看起来会更好。您可以轻松地编写一个类似以下名称的标签: &lt;product:image product='productInstance' /&gt; 并且为了提高可用性,您也可以让 tagLib 输出链接。

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

        【讨论】:

        • 感谢您的回答,已经完成了。我接下来要花更多的时间研究tagLib!
        【解决方案4】:

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

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

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

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

        【讨论】:

        • 感谢迈克尔的回复。它有效,但我想从 web-app 文件夹开始我的路径。 resource 关键字可以帮助我自动执行此操作。按照您的方式,我必须使用链接: /images/Nikon.jpg 。我可以只保存“Nikon.jpg”或“/images/Nikon.jpg”吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        • 1970-01-01
        • 2013-06-29
        • 2017-11-02
        • 2012-01-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多