简体   繁体   中英

add an image property to a domain class in Grails

I have a domain class in Grails and I want to add a picture attribute (the image of the user) A detailed answer will be helpful for a Grails beginner like me.

What will be the type of the attribute? How can I store it in a database (MySQL)?

I have implemented functionality like this in this way:

  1. First of all domain class. I add 3 properties to the class where I can store byte array with image and image properties like image type (gif, png, jpg) and image original name.

     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. Secondly, you need to remember to have proper type of form to upload image to your server:

     <g:uploadForm class="user-form"> Image: <g:field name="userImage" type="file" accept="image/*"/> </g:uploadForm>
  3. Thirdly, controller. 'create' action to get image from request and save it into database and 'getImage' action to get link to the image.

     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. In the end, rendering an image in view (userId is of course id of user whose you want an image):

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

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