简体   繁体   中英

Image property in domain class

i tried to add img field on my domain class, i run my app everyting is ok. When i try to add img i get this error,

Property carImg is type-mismatched

here is my domain-class

package carrentco


class Car {

    String brand
    String model
    String fuelType
    BigDecimal pricePerDay
    byte[] carImg


    static constraints = {
        brand(inList:["AUDI", "BMW", "MERCEDES", "NISSAN", "HONDA", "FORD"])
        model()
        fuelType(inList:["FUEL", "DIESEL", "AUTOGAS"])
        pricePerDay(min:0.0, max:1000.0)
        carImg(nullable:true, maxSize:1000000)
    }

}

here is what i add to my controller.

def displayCarImg = {
        def car = Car.get(params.id)
        response.contentType = "image/jpeg"
        response.contentLength = car?.carImg.length
        response.outputStream.write(car?.carImg)
    }

and here is my show.gsp

<img src="${createLink(action:'displayCarImg', id:carInstance?.id)}" />

something similar here

def viewPic(Long picId) {
        def photo = ChatUserPics.get( picId ?: params.id)
        if (photo) {
            byte[] image = photo.photo
            response.outputStream << image
        }
    }

Appears to have worked in that scenario, maybe you haven't followed any official documentations on all this..

I would highly recommend comparing storing images on file system vs db as a solution before rushing ahead. Personally using DB as a pointer - file system location.

If you have 100,000 users each having 10 images maybe most likely inexperienced and uploading 2mb files straight from phone camera. Now imagine backup time of that DB. VS migration costs in time if data needed replicating. DB issues and having to rely on gig db backups to restore..

Anyways you are holding the steering wheel and driving am a passenger and think it may be a bumpy road

If the image is small enough, like avatar or thumb, you can store it as a Base64-encoded String:

class Car {    
    String brand
    String carImg
}

upon saving in a controller you do:

car.carImg = new String( imageAsByteArray ).encodeAsBase64()

and display it in a GSP:

<img src="${car.carImg}"/>

One big advantage of such approach is that you don't need to fetch each of your images in a new request. Instead you have a single data page with all embedded images. This is extremely advantageous for mobile apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM