嗨,我是Grails和PostgreSQL的新手。我正在尝试制作一个存储用户数据的表单,并且希望能够上传多张照片。
服务:
Cars carInstance = new Cars()
carInstance.carimg = params.carimg.getBytes()
gsp:
<input type="file" id="carimg" name="carimg" multiple />
然后我在控制器中调用saveCar
动作,以保存用户将输入的所有数据。
我想以showCar
gsp的方式在图像中显示数据:
<img src="${createLink(controller: 'garage', action: 'getImage', params: ['id': Cars.id])}"/>
获取图像并将其传递到gsp的getImage
动作是这样的:
def getImage(){
def item = Cars.get(params.id.toLong())
byte[] imageInByte=item.carimg
response.contentType = 'image/png'
response.outputStream << imageInByte
response.outputStream.flush() }
在gsp中,它显示为空白边框,在左上角有图像,这意味着可能找不到图像。 如果我将二进制数据转换为字符串,它将显示正确的照片名称。 有什么建议么?问题出在我存储图像的方式还是尝试向图像显示二进制数据的方式?
答案 0 :(得分:0)
您的情况下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
}
}
在Controller中,我有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>
此外,您还需要更改上传方法。您可以找到信息here。