首页 > 解决方案 > Grails 2.5.11 / Postgresql 10,上传图片并在 GSP 中显示

问题描述

嗨,我是 Grails 和 PostgreSQL 的新手。我正在尝试制作一个存储用户数据的表单,并且我希望能够上传多张照片。

服务:

Cars carInstance = new Cars() 
carInstance.carimg = params.carimg.getBytes()

普惠制:

<input type="file" id="carimg" name="carimg" multiple />

我在控制器中调用saveCar操作来保存用户将输入的所有数据。

我想以showCar这种方式在 gsp 中显示带有图像的数据:

 <img src="${createLink(controller: 'garage', action: 'getImage', params: ['id': Cars.id])}"/>

getImage获取图像并将其传递给 gsp 的操作是这样的:

 def getImage(){
   def item = Cars.get(params.id.toLong())
   byte[] imageInByte=item.carimg
   response.contentType = 'image/png'
   response.outputStream << imageInByte
   response.outputStream.flush() }

在 gsp 中,它显示为一个空白边框,左角有一个图像,这意味着可能找不到图像。如果我将二进制数据转换为字符串,它会显示正确的照片名称。有什么建议么?问题在于我存储图像的方式或尝试将二进制数据显示到图像的方式?

标签: postgresqlgrailsgroovygsp

解决方案


Cars.id的情况是什么?也许它是一系列汽车,您需要对其进行迭代?

<g:each in="${Cars.list()}" var="car">
 <img src="${createLink(controller: 'garage', action: 'getImage', params: ['id': car.id])}"/>
</g:each>

编辑1:

根据您的回复,我创建了一个示例 grails(2.5.6) 项目。

领域:

class Car {
    String name
    byte[] photo

    static constraints = {
        photo maxSize: 1024 * 1024 * 2
    }
}

在控制器中,我有两种方法:

def show(Car carInstance) {
    respond carInstance
}

def showImage(int id) {
    def item = Car.get(id)

    byte[] imageInByte = item.photo

    response.contentType = 'image/png'
    response.outputStream << imageInByte
    response.outputStream.flush()
}

和 gsp 页面:

<g:fieldValue bean="${carInstance}" field="name"/>
<img src="${createLink(controller: 'Car', action: 'showImage', params: [id: carInstance.id])}"/>

并且图像已成功渲染。

编辑2:

抱歉,我想念您尝试使用多张图片进行的操作。

首先,您需要创建额外的域来存储照片:

class CarPhoto {
    byte[] photo

    static belongsTo = [car: Car]

    static constraints = {
        photo maxSize: 1024 * 1024 * 2
    }
}

并将此依赖项添加到 Car Domain:

class Car {
    String name
    static hasMany = [photos: CarPhoto]

    static constraints = {}
}

之后,您需要将这些更改应用于 showImage 操作:

def showImage(long id, long photo_id) {
    def car = Car.get(id)
    def photo = CarPhoto.findByCarAndId(car, photo_id)

    byte[] imageInByte = photo.photo

    response.contentType = 'image/png'
    response.outputStream << imageInByte
    response.outputStream.flush()
}

并到 gsp 页面:

<g:each in="${carInstance.photos}" var="photo">
    <img src="${createLink(controller: 'Car', action: 'showImage', params: [id: carInstance.id, photo_id: photo.id])}"/>
</g:each>

您还需要更改上传方法。你可以在这里找到信息。


推荐阅读