Display image in GSP (Grails), get links from the database

I am new to Grails. I am trying to show a thumbnail of images for each product on the site, for example:

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

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

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

But I can not replace the code / * 2 / with the place "Nikon.jpg" in / 1 * /, this causes a syntax error!

After a series of studies, I see that most tutorials show how to display an image that is stored directly in the database (for example, How to display an image in grails GSP? ), I'm not sure if this approach is better, but I still want to use the link to the image from the database.

I also tried to find the grails tag library to find any support tag, but without success. Can someone give me a hint?

+3
source share
4 answers

The correct syntax is to avoid syntax errors:

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

But I recommend you write your own tagLib, because it is actually very simple to write one, and your GSPs will look much nicer if you intend to use this code a lot. You can easily write a tag that will be called something like: <product:image product='productInstance' />and for added ease of use, you can make tagLib also display a link.

The ease of writing tagLibs is actually one of the best Grails features in my opinion.

+3
source

... , - :

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

, . :

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

imagePath ../../../web- app/personImages/imageName.img FileUploadService. 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')}" />
0

I needed a secure solution that was made in a 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 this purpouse, I used the Domain, where I store the image path, gsp for displaying images, and a controller for serving 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 am showing database images as follows

DoclistController Result

Hope this helps

0
source

Source: https://habr.com/ru/post/1776168/


All Articles