Saturday, October 19, 2013

Grails Mime Utility

In order to send emails using the grails mail plugin, I needed the mime type.  However, I had no idea how to get that correctly.  Fortunately, a quick google search turned up http://jira.grails.org/browse/GRAILS-6823, which asked for exactly what I was looking for.

Turns out Graeme did some work in 2.0 to put this feature in, but I don't think it's documented anywhere really.  So I thought I would do a quick post on this to help out others who are looking for this this same information.

Simply inject the bean into your service, controller, domain class, etc and call the getMimeTypeForExtension method.  Another tip: use the commons-io FilenameUtils.getExtension to get the extension from the file name without doing any manual parsing:

class MyController {
     DefaultMimeUtility grailsMimeUtility
    String getMimeTypeForFileName(String filename) {
          return grailsMimeUtility.getMimeTypeForExtension(FilenameUtils.getExtension(filename))
    }