繁体   English   中英

将图像属性添加到 Grails 中的域类

[英]add an image property to a domain class in Grails

我在 Grails 中有一个域类,我想添加一个图片属性(用户的图像)详细的答案对我这样的 Grails 初学者很有帮助。

属性的类型是什么? 如何将其存储在数据库(MySQL)中?

我以这种方式实现了这样的功能:

  1. 首先是域类。 我向类中添加了 3 个属性,我可以在其中存储带有图像和图像属性的字节数组,例如图像类型(gif、png、jpg)和图像原始名称。

     class User { byte[] image; String imageName; String imageContentType; static constraints = { image nullable: true, blank: true, maxSize: 1024 * 1024 * 20; //20MB imageName nullable: true, blank: true; imageContentType nullable: true, blank: true; } }
  2. 其次,您需要记住使用正确类型的表单将图像上传到您的服务器:

     <g:uploadForm class="user-form"> Image: <g:field name="userImage" type="file" accept="image/*"/> </g:uploadForm>
  3. 第三,控制器。 “创建”操作从请求中获取图像并将其保存到数据库中,“getImage”操作用于获取图像链接。

     class UserController { def create () { def imageMap = [:]; def imageContentType = parameters.componentImageImageForm?.getContentType(); if (imageContentType == null || !(imageContentType =~ "image/")) { imageMap.put("image", null); imageMap.put("imageName", null); imageMap.put("imageContentType", null); } else { imageMap.put("image", parameters.componentImageImageForm?.getBytes()); imageMap.put("imageName", parameters.componentImageImageForm?.getOriginalFilename()); imageMap.put("imageContentType", parameters.componentImageImageForm?.getContentType()); } def newUser = new User(imageMap); def validation = newUser.save(flush:true); //if(validation == null) { //validation failed //} else { //validation passed //} //you can return here some msg or something you need } def getImage(Long id) { def user = User.get(id); if (user != null) { response.contentType = user.imageContentType == null ? "image/jpeg" : user.imageContentType; response.contentLength = user.image == null ? 0 : user.image.size(); response.outputStream << user.image; } else { response.contentType = "image/jpeg"; response.contentLength = 0; response.outputStream << null; } } }
  4. 最后,在视图中呈现图像(userId 当然是您想要图像的用户的 id):

     <img src="${createLink(action: 'getImage', controller: 'user', id: userId)}"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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