Last updated by peyman 3 years ago
Simple Avatar Uploader
Many collaborative websites allow the user to upload small images or avatars to visually represent the user on the website. Grails makes the upload and display of these images almost trivial.In this example, we will not specify an exact size for the avatar, but use CSS scaling and assume a width-to-height ratio of 4:5.To start, you need to add two fields to your User domain class, a byte[] to hold the raw image and a String to hold the mime-type of the image:Domain Class: User.groovyclass User {
String userid
byte[] avatar
String avatarType static constraints = {
avatar(nullable:true, maxSize: 16384 /* 16K */)
avatarType(nullable:true)
}<fieldset> <legend>Avatar Upload</legend> <g:form action="upload_avatar" method="post" enctype="multipart/form-data"> <label for="avatar">Avatar (16K)</label> <input type="file" name="avatar" id="avatar" /> <div style="font-size:0.8em; margin: 1.0em;"> For best results, your avatar should have a width-to-height ratio of 4:5. For example, if your image is 80 pixels wide, it should be 100 pixels high. </div> <input type="submit" class="buttons" value="Upload" /> </g:form> </fieldset>
def upload_avatar = {
def user = User.current(session) // or however you select the current user // Get the avatar file from the multi-part request
def f = request.getFile('avatar') // List of OK mime-types
def okcontents = ['image/png', 'image/jpeg', 'image/gif']
if (! okcontents.contains(f.getContentType())) {
flash.message = "Avatar must be one of: ${okcontents}"
render(view:'select_avatar', model:[user:user])
return;
} // Save the image and mime type
user.avatar = f.getBytes()
user.avatarType = f.getContentType()
log.info("File uploaded: " + user.avatarType) // Validation works, will check if the image is too big
if (!user.save()) {
render(view:'select_avatar', model:[user:user])
return;
}
flash.message = "Avatar (${user.avatarType}, ${user.avatar.size()} bytes) uploaded."
redirect(action:'show')
}def avatar_image = {
def avatarUser = User.get(params.id)
if (!avatarUser || !avatarUser.avatar || !avatarUser.avatarType) {
response.sendError(404)
return;
}
response.setContentType(avatarUser.avatarType)
response.setContentLength(avatarUser.avatar.size())
OutputStream out = response.getOutputStream();
out.write(avatarUser.avatar);
out.close();
}img.avatar {
width: 6.0em;
height: 7.5em;
}img.avatar_small {
width: 4em;
height: 5em;
}img.avatar_tiny {
width: 2em;
height: 2.5em;
}<g:if test="${user.avatar}"> <img class="avatar" src="${createLink(controller:'user', action:'avatar_image', id:user.ident())}" /> </g:if>



