Displaying image in GSP (Grails), get link from database

岁酱吖の 提交于 2019-12-18 17:58:11

问题


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?


回答1:


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.




回答2:


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>



回答3:


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')}" />



回答4:


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

Hope this helps



来源:https://stackoverflow.com/questions/4243467/displaying-image-in-gsp-grails-get-link-from-database

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