image - 如何在编辑 View 上更新图像?

标签 image grails updates

在类(class)域上:

class Employee {

    String name
    ...
    ...
    byte[] picture
    static constraints = {
        name()
        .....
        picture (nullable:true, maxSize: 1048576 /* 16K */)
    }
}

在表单 View 上:
<div id="preview" class="thumbnail">
    <a href="#" id="file-select" class="btn btn-default">Choose File</a>
    <img class="img-circle" alt="User Image" style="width:100%;"
         src="${employeeInstance?.picture? 
         createLink(controller:'employee', action:'image',
         id:employeeInstance.id):assetPath(src: 'user-default.png')}"/>
</div>
<input type="file" id="picture" name="picture" class="form-control" />
<span class="alert alert-info" id="file-info">No file yet</span>

在 Controller 上:
def image() {
    def avatarUser = Employee.get(params.id)
    if (!avatarUser || !avatarUser.picture){//|| !avatarUser.avatarType) {
        response.sendError(404)
        return
    }
    response.contentType = "image/jpeg"//avatarUser.avatarType
    response.contentLength = avatarUser.picture.size()
    OutputStream out = response.outputStream
    out.write(avatarUser.picture)
    out.close()
}

protected void notFound() {
    request.withFormat {
        form multipartForm {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'employee.label', default: 'Employee'), params.id])
            redirect action: "index", method: "GET"
        }
    }
}

我上传图像并将其显示在“编辑” View 上,但是即使我不更改图片,在更新时也不会保留该图像。

最佳答案

没有更新方法,很难知道您如何处理更新。但是我不太了解,所以当您展示图像时,我想将其放在<img>标记中,然后,如果用户在不更改图像的情况下更新信息,所有数据都将以params发送,但在这种情况下,avatarUser.picture会因为它没有一个字段与您从呈现给用户的表单中发送的参数相匹配,所以应为null。也许如果您有一个字段被 Controller 接收,因为从表单发送的图像在表单中的图像字节编码为base64可能是一种解决方案,虽然不是很干净,但可以解决。问题是我对您的其余实现一无所知,但就我所读的内容而言,我认为这可能有效:
在更新 View 中,隐藏标签的图像以base 64编码:

<input type="hidden" name="name-you-expect-in-update-controller" value="${Employee.picture.encodeBase64().toString()}" />

这样,您将在更新 Controller 中获得带有base64编码的字符串的参数,然后将其解码如下:
byte[] image= encodedImage.decodeBase64()

然后像现在一样在方法image()中使用它。

希望我走上了想要解决问题的轨道!

关于image - 如何在编辑 View 上更新图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29829942/

相关文章:

python - django-图像裁剪不起作用

android - 如何在 ListView 中实现延迟加载的图像列表

android - 如何在用户触摸事件时在 xml 布局上 move 图像?

angular - 是否可以有一个 body 渲染 Angular 4

grails - 是否可以将 Groovy Expandos 的集合绑定(bind)到碧 Jade 报告?

sql - 指定一个触发器来更新时间戳字段

hibernate - 使用Spring data jpa批量更新

c++ - 从资源中加载图像并转换为内存中的位图

url - Grails 2.3.x : get the value of URL parameters

ios - Apple IOs 更新,旧版本会保留吗?